Problem Description
John has n tasks to do. Unfortunately, thetasks are not independent and the execution of one task is
only possible if other tasks have alreadybeen executed.
Input
The input will consist of several instancesof 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 isthe
number of direct precedence relations betweentasks. After this, there will be m lines with two integers
i and j, representing the fact that task imust be executed before task j.
An instance with n = m = 0 will finish theinput.
Output
For each instance, print a line with nintegers 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。那么,所有变量从小到大排列起来应该是什么样子的呢?
把每个变量看成一个点,“小于”关系看成有向边,则得到了一个有向图。这样,我们的任务实际上是把一个图的所有结点排序,使得每一条有向边(u,v)对应的u都排在v的前面。
用dfs完成拓扑排序,在访问完一个结点之后吧它加到当前拓扑序的首部。
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> #define max 100+5 int c[max],topo[max],t,n,G[max][max]; int dfs(int u) { int v; c[u] = -1; //访问标志,-1为正在访问,0是未访问,1是已经访问 for(v = 1; v <= n; v++) if(G[u][v]) { if(c[v] < 0) return 0; else if(!c[v] && !dfs(v)) return 0; } c[u] = 1; topo[--t] = u; return 1; } int toposort() { int i; t = n; memset(c,0,sizeof(c)); for(i = 1; i <= n; i++) if(!c[i] && !dfs(i)) return 0; return 1; } int main() { int m,i; while(scanf("%d%d",&n,&m),n || m) { int u,v; memset(G,0,sizeof(G)); for(i = 0 ; i < m ; i++) { scanf("%d%d",&u,&v); G[u][v] = 1; } if(toposort()) { for(i = 0; i < n-1; i++) printf("%d ",topo[i]); printf("%d\n",topo[i]); } } return 0; }