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
问题简述:(略)
问题分析:
这是一个拓扑排序的裸题,按照拓扑排序算法计算即可。
这里采用邻接矩阵(二维数组)存储图。一般而言,只有节点规模小的情况下,图才可以使用邻接矩阵表示,不然就太费存储了。
程序说明:
下标为0的存储单元没有使用,浪费了存储,代码的下标转换不用做了,代码相对简洁。
输出结果(解)可能是多种,本程序计算样例时,结构虽然与给定的结果有所不同,但是也AC了。题目还是不够严密啊。
题记:(略)
参考链接:(略)
AC的C++语言程序如下:
/* UVA10305 Ordering Tasks */
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
const int N = 100 + 1;
int g[N][N];
int degreein[N];
int ans[N];
int n, m;
void toposort()
{
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
if(g[i][j])
degreein[j]++;
// 从节点号小的开始寻找
for(int i = 1; i <= n; i++) {
int k = 1;
while(degreein[k] != 0)
k++;
ans[i] = k;
degreein[k] = -1;
// 去除已经找出的节点的入度
for(int j = 1; j <= n; j++)
if(g[k][j])
degreein[j]--;
}
}
int main()
{
while(~scanf("%d%d", &n, &m) && (n || m)) {
// 初始化
memset(g, 0, sizeof(g));
memset(degreein, 0, sizeof(degreein));
memset(ans, 0, sizeof(ans));
// 读入数据
int u, v;
for(int i = 1; i <= m; i++) {
scanf("%d%d", &u, &v);
g[u][v] = 1;
}
// 拓扑排序
toposort();
// 输出结果
for(int i = 1; i < n; i++)
printf("%d ", ans[i]);
printf("%d\n", ans[n]);
}
return 0;
}