P1137 旅行计划

题目描述

小明要去一个国家旅游。这个国家有N个城市,编号为1~N,并且有M条道路连接着,小明准备从其中一个城市出发,并只往东走到城市i停止。

所以他就需要选择最先到达的城市,并制定一条路线以城市i为终点,使得线路上除了第一个城市,每个城市都在路线前一个城市东面,并且满足这个前提下还希望游览的城市尽量多。

现在,你只知道每一条道路所连接的两个城市的相对位置关系,但并不知道所有城市具体的位置。现在对于所有的i,都需要你为小明制定一条路线,并求出以城市i为终点最多能够游览多少个城市。

输入输出格式

输入格式:

 

输入的第1行为两个正整数N, M。

接下来M行,每行两个正整数x, y,表示了有一条连接城市x与城市y的道路,保证了城市x在城市y西面。

 

输出格式:

 

输出包括N行,第i行包含一个正整数,表示以第i个城市为终点最多能游览多少个城市。

 

输入输出样例

输入样例#1: 复制
5 6
1 2
1 3
2 3
2 4
3 4
2 5
输出样例#1: 复制
1
2
3
4
3

说明

均选择从城市1出发可以得到以上答案。

对于20%的数据,N ≤ 100;

对于60%的数据,N ≤ 1000;

对于100%的数据,N ≤ 100000,M ≤ 200000。

 

 

拓扑排序+bfs+dp

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define inf 2147483647
const ll INF = 0x3f3f3f3f3f3f3f3fll;
#define ri register int
template <class T> inline T min(T a, T b, T c)
{
    return min(min(a, b), c);
}
template <class T> inline T max(T a, T b, T c)
{
    return max(max(a, b), c);
}
template <class T> inline T min(T a, T b, T c, T d)
{
    return min(min(a, b), min(c, d));
}
template <class T> inline T max(T a, T b, T c, T d)
{
    return max(max(a, b), max(c, d));
}
#define scanf1(x) scanf("%d", &x)
#define scanf2(x, y) scanf("%d%d", &x, &y)
#define scanf3(x, y, z) scanf("%d%d%d", &x, &y, &z)
#define scanf4(x, y, z, X) scanf("%d%d%d%d", &x, &y, &z, &X)
#define pi acos(-1)
#define me(x, y) memset(x, y, sizeof(x));
#define For(i, a, b) for (int i = a; i <= b; i++)
#define FFor(i, a, b) for (int i = a; i >= b; i--)
#define bug printf("***********\n");
#define mp make_pair
#define pb push_back
const int N = 1000005;
const int mod=100003;
// name*******************************
struct edge
{
    int to,next;
} e[N];
int Head[N];
int tot=0;
int n,m;
queue<int>que;
int in[N];
int f[N];
// function******************************
void add(int u,int v)
{
    e[++tot].to=v;
    e[tot].next=Head[u];
    Head[u]=tot;
}
void bfs(int x)
{
    que.push(x);
    while(!que.empty())
    {
        int u=que.front();
        que.pop();
        for(int p=Head[u]; p; p=e[p].next)
        {
            int v=e[p].to;
            f[v]=max(f[v],f[u]+1);
            if(in[v]==1) que.push(v);
            else in[v]--;
        }
    }
}

//***************************************
int main()
{
//    ios::sync_with_stdio(0);
//    cin.tie(0);
    // freopen("test.txt", "r", stdin);
    //  freopen("outout.txt","w",stdout);
    cin>>n>>m;

    For(i,1,m)
    {
        int a,b;
        scanf("%d%d",&a,&b);
        add(a,b);
        in[b]++;
    }

    For(i,1,n)
        if(in[i]==0)
        {
            f[i]=1;
            bfs(i);
        }
    
    For(i,1,n)
        printf("%d\n",f[i]);
    

    return 0;
}

 

posted @ 2018-04-05 22:47  planche  阅读(170)  评论(0)    收藏  举报