拓扑排序模版题型:
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,要求对所有任务进行排序,使得前面的任务应该先于后面的任务,输出一组解
本题有坑!见代码
#include <cstdio> #include <cstring> #include <algorithm> #define maxn 4000 int c[maxn], topo[maxn], t, n, m; bool G[maxn][maxn]; bool dfs(int u) { c[u] = -; ; v < n; v++) { if (G[u][v]) ) return false; else if (!c[v]) dfs(v); } c[u] = ; topo[--t] = u; return true; } bool toposort() { t = n; memset(c, , sizeof c); ; u < n; u++) if (!c[u]) if (!dfs(u)) return false; return true; } int main() { && n)//因为m的值可能为0! //while (scanf("%d%d", &n, &m) && m && n) { memset(G, , sizeof G); int _u, _v; while (m--) scanf(][_v - ] = ; if (toposort()) { ; i < n - ; i++) printf(); printf(] + ); } else printf("No\n"); } system("pause"); ; }