拓扑排序模板
1 # include <stdio.h> 2 # include <string.h> 3 # define MAX 1000 4 int n,m,indegree[MAX]; 5 int G[MAX][MAX],q[MAX]; 6 void toposort() 7 { 8 int i,j,k; 9 for(i=0;i<n;) 10 { 11 for(j=1;j<=n;j++) //从最小的点开始找。 12 { 13 if(indegree[j] == 0) 14 { 15 indegree[j]--; 16 q[i++]=j; 17 for(k=1;k<=n;k++) 18 if(G[j][k]) 19 indegree[k]--; 20 21 } 22 } 23 } 24 } 25 int main() 26 { 27 int i,a,b; 28 while(scanf("%d%d",&n,&m) == 2) 29 { 30 memset(G,0,sizeof(G)); 31 memset(indegree,0,sizeof(indegree)); 32 for(i=1;i<=m;i++) 33 { 34 scanf("%d%d",&a,&b); 35 if(G[a][b] == 0) 36 { 37 G[a][b]=1; 38 indegree[b]++; 39 } 40 } 41 toposort(); 42 for(i=0;i<n;i++) 43 { 44 if(i != n-1) 45 printf("%d ",q[i]); 46 else 47 printf("%d",q[i]); 48 } 49 printf("\n"); 50 } 51 return 0; 52 }