UVA Ordering Tasks

拓扑排序模板题解析
本文解析了一道关于任务执行顺序的问题,通过拓扑排序算法确定了各任务间的依赖关系及可能的执行顺序。输入包括任务数量及依赖关系,输出为一个合法的任务执行序列。

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


题目是说John有n个任务要做,但是这些任务并不是相互独立的,而是要先做完某个任务才能做下一个任务

拓扑排序模板题。

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int a[510][510];
int num[510];
int book[510];
int main(){
	int n,m;
	while(~scanf("%d%d",&n,&m)){
		if(!n&&!m) break;
		memset(a,0,sizeof(a));
		memset(num,0,sizeof(num));
		memset(book,0,sizeof(book));
		while(m--){
			int x,y;
			cin>>x>>y;
			//两点之间的边加一 
			a[x][y]++;
			//入度加一 
			num[y]++;
		}
		for(int i=1;i<=n;i++){
			int j=1;
			//寻找下一个入度不为零的点 
			while(num[j]!=0) j++;
			//将其变为-1 
			num[j]=-1;
			//记录这个点 
			book[i]=j;
			for(int k=1;k<=n;k++){
				//删除此点之后要将与他相关联的边删掉
				//与他相邻的点入度-1 
				if(a[j][k]){
					num[k]--;
				}
			}
		}
		for(int i=1;i<=n-1;i++) cout<<book[i]<<' ';
		cout<<book[n]<<endl;
	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值