UVA - 10305 - Ordering Tasks(拓扑排序)
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. 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
拓扑排序的题,给你一个有向图,输出拓扑序列
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
int n, m;
const int maxn = 110;
int mp[maxn][maxn], indegree[maxn], ans[maxn];
queue<int> q;
void topologic(){
int cnt = 0;
for (int i = 1; i <= n; i++){
if (indegree[i] == 0)
q.push(i); //把所有入度为0的点压入队中
}
while (!q.empty()){
int now = q.front();
q.pop();
ans[cnt++] = now;
for (int i = 1; i <= n; i++){
int a = mp[now][i];
if(mp[now][i]!=0){
indegree[i]--;
if(indegree[i] == 0)
q.push(i); //把所有入度为0的点压入队中
}
}
}
printf("%d", ans[0]);
for(int i = 1; i < cnt; i++)
printf(" %d", ans[i]);
printf("\n");
}
int main()
{
while(scanf("%d %d", &n, &m)!=EOF){
if(!n && !m)
break;
memset(mp, 0, sizeof(mp));
memset(indegree, 0, sizeof(indegree));
for(int i = 0; i < m; i++){
int a, b;
scanf("%d %d", &a, &b);
mp[a][b] = 1;
indegree[b]++;
}
topologic();
}
return 0;
}
该博客介绍了UVA在线判题平台上的10305题——Ordering Tasks,这是一道关于拓扑排序的问题。题目要求根据有向图中任务的依赖关系,找出任务的可行执行顺序。输入包含任务数量n和直接依赖关系m,输出应为一个拓扑排序后的任务序列。示例输入和输出展示了如何解决这个问题。
594

被折叠的 条评论
为什么被折叠?



