UVaOJ 10305 Ordering Tasks(拓扑排序)

本文介绍了一种基于图的拓扑排序算法解决任务依赖问题的方法。通过建立有向图表示任务间的前后关系,并使用优先队列实现拓扑排序,最终输出一个符合任务依赖关系的任务执行顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Ordering Tasks

John has n tasks to do. Unfortunately, the tasks are not independent and the execution of one task isonly 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 containingtwo integers, 1 ≤ n ≤ 100 and m. n is the number of tasks (numbered from 1 to n) and m is thenumber of direct precedence relations between tasks. After this, there will be m lines with two integersi 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个任务要做,每个任务都不是独立的,做一个任务之前必须将它的前驱任务全部做完。现在给出n个任务和m个任务关系,求出一个做任务的顺序。

解题思路:把每个任务看成点,任务之间的前后关系看成边,那么会的得到一个有向图。然后对这个图求拓扑排序即可。

代码如下:

#include <bits/stdc++.h>
#define INF 1e9 + 5
using namespace std;
const int maxn = 10005;
struct Edge
{
	int to;
	int next;
};
Edge edge[maxn];
int head[maxn],degree[maxn],topo[maxn];
bool vis[maxn];
int n,m,e;

void init()
{
	e = 0;
	memset(vis,0,sizeof(vis));
	memset(head,-1,sizeof(head));
	memset(degree,0,sizeof(degree));
}

void add_edge(int from,int to)
{
	degree[to]++;
	edge[e].to = to;
	edge[e].next = head[from];
	head[from] = e++;
}

void toposort()
{
	priority_queue<int> que;
	for(int i = 1;i <= n;i++)
		if(!degree[i])
			que.push(i);
	int pos = 1;
	while(que.size()){
		int u = que.top();
		que.pop();
		topo[pos++] = u;
		for(int i = head[u];i != -1;i = edge[i].next){
			degree[edge[i].to]--;
			if(!degree[edge[i].to])
				que.push(edge[i].to);
		}
	}
}

int main(void)
{
	int a,b;
	while(scanf("%d %d",&n,&m) != EOF && n + m){
		init();
		while(m--){
			scanf("%d %d",&a,&b);
			vis[a] = vis[b] = 1;
			add_edge(a,b);
		}
		toposort();
		printf("%d",topo[1]);
		for(int i = 2;i <= n;i++)
			printf(" %d",topo[i]);
		printf("\n");
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值