ACM之纠结篇:Ordering Tasks

来源:互联网 发布:詹姆斯五项数据第一 编辑:程序博客网 时间:2024/06/05 09:37

Ordering Tasks

Input: standard input

Output: standard output

Time Limit: 1 second

Memory Limit: 32 MB

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. nis the number of tasks (numbered from 1to 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


一开始被这题坑了很久,不淡定啊不淡定。。。
题目意思很容易就看明白了,可是看这样例输入和输出,就觉得怎么也不对啊,为什么是这个输出啊???
我就在那纠结是不是输出错了。。。
然后就先不做这题了,先去看其他的题目了。等到其他的题目都做的差不多了,又看到了这题。然后,然后,然后我又看了遍题目。
感觉意思还是一样啊,怎么办???
算了,不管了,就按我自己想的去写吧。代码很快就写好了,然后输入了这些数,我的输出竟然是4 1 5 2 3。。。
一下子又不管三七二十一,交上去再说。
结果。。。AC了。。。不敢相信。。。
然后我回来看了一下输出:For each instance, print a line with n integers representing the tasks in a possible order of execution.

。。。又不淡定了,possible,possible,possible,possible,possible。。。a possible order of。。。

懂了~~~噗!

下面是我AC的代码:

#include <set>
#include <cmath>
#include <stack>
#include <queue>
#include <cstdio>
#include <vector>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
using namespace std;

int n, t;
int a[110], b[110];
int map[110][110];

void dfs(int z)
{
a[z] = 1;
for (int i = 0; i < n; i++)
{
if(map[z][i] && !a[i]) dfs(i);
}
b[--t] = z;
}

int main()
{
int m;

while (scanf("%d%d", &n, &m) && (n || m))
{
t = n;
memset(a, 0, sizeof(a));
memset(b, 0, sizeof(b));
memset(map, 0, sizeof(map));

for (int i = 0; i < m; i++)
{
int x, y;
scanf("%d%d", &x, &y);
map[x - 1][y - 1] = 1;
}

for (int i = 0; i < n; i++)
{
if (!a[i]) dfs(i);
}

for (int i = 0; i < n - 1; i++)
{
printf("%d ", b[i] + 1);
}
printf("%d\n", b[n - 1] + 1);
}

return 0;
}

0 0