拓扑排序模版题型:
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
For each instance, print a line with n integers representing the tasks in a possible order of execution.
Sample Input
5 4 1 2 2 3 1 3 1 5 0 0
Sample Output
1 4 2 5 3
题目大意
给出n 任务个数,m组任务关系(u,v),即先有u,才能有v,要求对所有任务进行排序,使得前面的任务应该先于后面的任务,输出一组解
本题有坑!见代码
1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 #define maxn 4000 5 6 int c[maxn], topo[maxn], t, n, m; 7 bool G[maxn][maxn]; 8 9 bool dfs(int u) 10 { 11 c[u] = -1; 12 for (int v = 0; v < n; v++) 13 { 14 if (G[u][v]) 15 if (c[v] < 0) 16 return false; 17 else if (!c[v]) 18 dfs(v); 19 } 20 c[u] = 1; 21 topo[--t] = u; 22 return true; 23 } 24 25 bool toposort() 26 { 27 t = n; 28 memset(c, 0, sizeof c); 29 for (int u = 0; u < n; u++) 30 if (!c[u]) 31 if (!dfs(u)) 32 return false; 33 return true; 34 } 35 36 int main() 37 { 38 while (scanf("%d%d", &n, &m) ==2 && n)//因为m的值可能为0! 39 //while (scanf("%d%d", &n, &m) && m && n) 40 { 41 memset(G, 0, sizeof G); 42 int _u, _v; 43 while (m--) 44 scanf("%d%d", &_u, &_v), G[_u - 1][_v - 1] = 1; 45 if (toposort()) 46 { 47 for (int i = 0; i < n - 1; i++) 48 printf("%d ", topo[i] + 1); 49 printf("%d\n", topo[n - 1] + 1); 50 } 51 else 52 printf("No\n"); 53 } 54 system("pause"); 55 return 0; 56 }