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+;
const int maxn=1e2+;
const double eps = 1e-;
int topo[maxn], c[maxn], z;
int G[maxn][maxn];
int n, m;
bool dfs(int u)
{
c[u] = -;
for(int i = ; i <= n; i++){
if(G[u][i]==) continue;
if(c[i]==-) return false;///如果存在环,那么返回false;因为-1表示这条链还没寻找结束,
///如果一直寻找,找到了原来出现过的,那么存在环。
if(c[i]==&&G[u][i]){
if(dfs(i)==false) return false;
}
}
topo[z-] = u;
c[u] = ;
z--;
return true;
}
bool topoSort()
{
memset(c, , sizeof c);
z = n;
for(int i = ; i <= n; i++){
if(c[i]==){
if(dfs(i)==) return false;
}
}
return true;
}
int main()
{
while(scanf("%d%d",&n,&m)==&&(n+m))
{
int u, v;
memset(G, , sizeof G);
for(int i = ; i < m; i++){
scanf("%d%d",&u,&v);
G[u][v] = ;
}
topoSort();
printf("%d",topo[]);
for(int i = ; i < n; i++){
printf(" %d",topo[i]);
}
printf("\n");
}
return ;
}