Ordering Tasks UVA

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 nish 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
 
/**
题目:Ordering Tasks UVA - 10305
链接:https://vjudge.net/problem/UVA-10305
题意:给定一个有向无环图,求拓扑序列。
思路:
对一条链,从后往前存入到数组的头部。
如:5->4->3->2; 那么存到数组为: a[] = {5,4,3,2};

其他链要么和这条链尾部有交集,其他没有交集。由于交集处已经存进去了,为交集存入的肯定是放在数组的头部。
这样可以保证。

如果存在环,不存在拓扑序列。
*/

#include <iostream>
#include <cstdio>
#include <vector>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
typedef long long LL;
const int mod=1e9+7;
const int maxn=1e2+5;
const double eps = 1e-12;
int topo[maxn], c[maxn], z;
int G[maxn][maxn];
int n, m;
bool dfs(int u)
{
    c[u] = -1;
    for(int i = 1; i <= n; i++){
        if(G[u][i]==0) continue;
        if(c[i]==-1) return false;///如果存在环,那么返回false;因为-1表示这条链还没寻找结束,
        ///如果一直寻找,找到了原来出现过的,那么存在环。
        if(c[i]==0&&G[u][i]){
            if(dfs(i)==false) return false;
        }
    }
    topo[z-1] = u;
    c[u] = 1;
    z--;
    return true;
}
bool topoSort()
{
    memset(c, 0, sizeof c);
    z = n;
    for(int i = 1; i <= n; i++){
        if(c[i]==0){
            if(dfs(i)==0) return false;
        }
    }
    return true;
}
int main()
{
    while(scanf("%d%d",&n,&m)==2&&(n+m))
    {
        int u, v;
        memset(G, 0, sizeof G);
        for(int i = 0; i < m; i++){
            scanf("%d%d",&u,&v);
            G[u][v] = 1;
        }
        topoSort();
        printf("%d",topo[0]);
        for(int i = 1; i < n; i++){
            printf(" %d",topo[i]);
        }
        printf("
");
    }
    return 0;
}
原文地址:https://www.cnblogs.com/xiaochaoqun/p/6897625.html