UVA - 10305
Time Limit: 3000MS | Memory Limit: Unknown | 64bit IO Format: %lld & %llu |
Description
Problem F
Ordering Tasks
Input: standard input
Output: standard output
Time Limit: 1 second
Memory Limit: 32 MB
John has n tasks to do. Unfortunately, the tasks are not independent and the execution of one task is only possible if other tasks have already been executed.
Input
The input will consist of several instances of the problem. Each instance begins with a line containing two integers, 1 <= n <= 100 and m. n is the number of tasks (numbered from 1 to n) and m is the number of direct precedence relations between tasks. After this, there will be m lines with two integers i and j, representing the fact that task i must be executed before task j. An instance with n = m = 0 will finish the input.
Output
5 4
1 2
2 3
1 3
1 5
0 0
1 4 2 5 3
(The Joint Effort Contest, Problem setter: Rodrigo Malta Schmidt)
Source
白书上的拓扑排序!
AC代码:
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; int flag, n, m; int topo[110], num[110], s[110][110]; bool dfs(int site) { num[site]=-1; for(int i=1; i<=n; i++) if(s[site][i]&&(num[i]<0||(!num[i]&&!dfs(i)))) return false; num[site]=1; topo[--flag]=site; return true; } bool toposort() { flag=n; memset(num,0,sizeof(num)); for(int i=1; i<=n; i++) if(!num[i]&&!dfs(i)) return false; return true; } int main() { int x,y,count; while(scanf("%d%d",&n,&m)!=EOF) { if(!n&&!m) break; memset(s,0,sizeof(s)); for(count=0; count<m; count++) { scanf("%d%d",&x,&y); s[x][y]=1; } if(toposort()) for(count=0; count<n-1; count++) printf("%d ",topo[count]); printf("%d\n",topo[count]); } return 0; }
UVA - 10305 - Ordering Tasks (拓扑排序!)
原文地址:http://blog.csdn.net/u014355480/article/details/41967745