拓扑排序模板题……
#include<bits/stdc++.h> using namespace std; const int maxn=105; int in[maxn],v[maxn][maxn],path[maxn],n,cnt; queue<int>qq; void tuopu() { while(!qq.empty()) { int t=qq.front(); qq.pop(); path[cnt++]=t; for(int j=1; j<=n; j++) if(v[t][j]) { v[t][j]=0; in[j]--; } for(int i=1; i<=n; i++) if(in[i]==0) { qq.push(i); in[i]=-1; } } } int main() { int t; while(scanf("%d",&n)==1) { cnt=0; memset(in,0,sizeof(in)); memset(v,0,sizeof(v)); for(int i=1; i<=n; i++) { while(scanf("%d",&t)==1&&t) { v[i][t]=1; in[t]++; } } for(int i=1; i<=n; i++) { if(in[i]==0) { qq.push(i); in[i]=-1; break; } } tuopu(); for(int i=0; i<cnt; i++) printf("%d ",path[i]); printf("\n"); } return 0; }