您的位置:首页 > 其它

UVA Ordering Tasks

2017-07-25 17:13 239 查看
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
<<endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: