洛谷P1137 旅行计划

 1 //拓扑排序 
 2 #include<bits/stdc++.h>
 3 #include<queue>
 4 using namespace std;
 5 const int maxn=100005;
 6 const int maxm=200005;
 7 struct edge{
 8     int to;edge *Nex;
 9 }tmp[maxm],*head[maxn];
10 int top=-1;
11 bool v[maxn];
12 inline void add(int x,int y)
13 {
14     tmp[++top].to=y;tmp[top].Nex=head[x];head[x]=&tmp[top];
15 }
16 queue<int> q;
17 int n,m,du[maxn],dis[maxn];
18 void topo()
19 {
20     for(int i=1;i<=n;++i) if(!du[i]) q.push(i),dis[i]=1;
21     while(!q.empty())
22     {
23         int p=q.front();q.pop();
24         for(edge *i=head[p];i!=NULL;i=i->Nex)
25         {
26             dis[i->to]=max(dis[i->to],dis[p]+1);
27             --du[i->to];
28             if(!du[i->to]) q.push(i->to); 
29         }
30     }
31 } 
32 int main()
33 {
34     scanf("%d%d",&n,&m);
35     for(int i=1,x,y;i<=m;++i) scanf("%d%d",&x,&y),add(x,y),++du[y];
36     topo();
37     for(int i=1;i<=n;++i) printf("%d
",dis[i]);
38     return 0;
39 }
原文地址:https://www.cnblogs.com/yu-xing/p/10315196.html