标签:
1 #include<cstdio> 2 #include<cstring> 3 #include<vector> 4 #include<queue> 5 #include<algorithm> 6 using namespace std; 7 8 int G[505][505]; 9 int indegree[505]; 10 int topo[505]; 11 int t,n,m; 12 void toposort() 13 { 14 t=0; 15 priority_queue<int,vector<int>,greater<int> >q; 16 for(int i=1;i<=n;i++) 17 { 18 if(indegree[i]==0) 19 q.push(i); 20 } 21 int temp; 22 while(!q.empty()) 23 { 24 temp=q.top(); 25 topo[t++]=temp; 26 q.pop(); 27 for(int i=1;i<=n;i++) 28 { 29 if(G[temp][i]) 30 { 31 indegree[i]--; 32 if(indegree[i]==0) 33 q.push(i); 34 } 35 } 36 } 37 } 38 39 40 int main() 41 { 42 //freopen("in.txt","r",stdin); 43 int i,a,b; 44 while(scanf("%d%d",&n,&m)!=EOF) 45 { 46 memset(indegree,0,sizeof(indegree)); 47 memset(G,0,sizeof(G)); 48 for(i=0;i<m;i++) 49 { 50 scanf("%d%d",&a,&b); 51 if(!G[a][b]) 52 indegree[b]++; 53 G[a][b]=1; 54 } 55 toposort(); 56 for(i=0;i<n-1;i++) 57 printf("%d ",topo[i]); 58 printf("%d\n",topo[i]); 59 } 60 return 0; 61 }
标签:
原文地址:http://www.cnblogs.com/homura/p/4727536.html