【luogu1137】旅行计划 [拓扑排序]

P1137 旅行计划

``` 1 #include<iostream>
2 #include<cstdio>
3 #include<queue>
4 #include<cstring>
5 #include<cmath>
6 #include<stack>
7 #include<algorithm>
8 using namespace std;
9 #define ll long long
10 #define rg register
11 const int N=100000+5,M=200000+5,inf=0x3f3f3f3f,P=19650827;
12 int n,m,r[N],f[N];
13 template <class t>void rd(t &x)
14 {
15     x=0;int w=0;char ch=0;
16     while(!isdigit(ch)) w|=ch=='-',ch=getchar();
17     while(isdigit(ch)) x=(x<<1)+(x<<3)+(ch^48),ch=getchar();
18     x=w?-x:x;
19 }
20
22 struct edge{int v,nxt;}e[M];
25 }
26
27 queue<int> q;
28 void topsort(){
29     for(rg int i=1;i<=n;++i)
30     if(!r[i]) q.push(i),f[i]=1;
31     while(!q.empty()){
32         int u=q.front();q.pop();
34             int v=e[i].v;
35             --r[v];
36             if(!r[v]) q.push(v),f[v]=f[u]+1;
37         }
38     }
39 }
40
41 int main(){
42     memset(r,0,sizeof(r));
43     rd(n),rd(m);
44     for(rg int i=1;i<=m;++i){
45         int u,v;
46         rd(u),rd(v);
48     }
49     topsort();
50     for(rg int i=1;i<=n;++i) printf("%d\n",f[i]);
51     return 0;
52 }
53  ```