题目连接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1246
拓扑排序
lrj167
1 #include<cstdio> 2 #include<cstring> 3 #include<set> 4 #include<iostream> 5 #include<cctype> 6 #include<string> 7 #include<sstream> 8 #include<algorithm> 9 #include<map> 10 #define LL long long 11 using namespace std; 12 const int maxn=110; 13 int u,v; 14 int n,m; 15 int t; 16 int top[maxn],vis[maxn]; 17 int p[maxn][maxn]; 18 int dfs(int u) 19 { 20 vis[u]=-1; 21 for(int v=1;v<=n;v++) if(p[u][v]) 22 { 23 if(vis[v]<0) return 0; 24 else if(!vis[v]&&!dfs(v)) return 0; 25 } 26 vis[u]=1; 27 top[t--]=u; 28 return 1; 29 } 30 int main() 31 { 32 while(scanf("%d%d",&n,&m)&&(n||m)) 33 { 34 memset(p,0,sizeof(p)); 35 memset(vis,0,sizeof(vis)); 36 for(int i=0;i<m;i++) 37 { 38 scanf("%d%d",&u,&v); 39 p[u][v]=1; 40 } 41 t=n; 42 for(int i=1;i<=n;i++) if(!vis[i]) 43 dfs(i); 44 for(int i=1;i<n;i++) 45 printf("%d ",top[i]); 46 printf("%d\n",top[n]); 47 } 48 }
时间: 2024-10-15 20:45:18