hdu 1285 拓扑排序
1 /* 2 题意:中文题 3 4 题解:拓扑排序 5 */ 6 #include <cstdio> 7 #include <cstring> 8 9 #define MAXN 505 10 int toposort(int n,int mat[][MAXN],int* ret){ 11 int d[MAXN],i,j,k; 12 for (i=0;i<n;i++) 13 for (d[i]=j=0;j<n;d[i]+=mat[j++][i]); 14 for (k=0;k<n;ret[k++]=i){ 15 for (i=0;d[i]&&i<n;i++); 16 if (i==n) 17 return 0; 18 for (d[i]=-1,j=0;j<n;j++) 19 d[j]-=mat[i][j]; 20 } 21 return 1; 22 } 23 24 int ans[MAXN]; 25 int gra[MAXN][MAXN]; 26 27 int main(void) 28 { 29 int n,m; 30 while (~scanf("%d%d",&n,&m)) 31 { 32 memset(gra,0,sizeof(gra)); 33 while (m--) 34 { 35 int p1,p2; 36 scanf("%d%d",&p1,&p2); 37 p1--; 38 p2--; 39 gra[p1][p2] = 1; 40 } 41 toposort(n,gra,ans); 42 printf("%d",ans[0]+1); 43 for(int i=1; i<n; i++) 44 printf(" %d",ans[i]+1); 45 printf("\n"); 46 } 47 return 0; 48 }