Ordering Tasks (uva10305)(DFS判断有向环)(拓扑排序)

原题目:

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

中文概要:

假设有n个变量,还有m个二元组(u,v),分别表示变量u小于v,那么,所有变量从小到大排列起来应该是什么样子,例如,有四个变量a,b,c,d,若已知a<b,c<b,d<c,则这4个变量的排序可能是a<d<c<b,尽管还有其他可能,只需找出一个即可

【分析】

把每个变量看成一个点,小于关系看成有向边,则得到了一个有向图,这样,我们的实际任务是把一个图的所有节点排序,使得每一条有向边(u,v)所对应的u都排在v的前面,在图论中,这种问题成为拓扑排序。

不难发现,如果图中存在有向环,则不存在拓扑排序,反之则存在。

#include<algorithm>
#include<vector>
#include<queue>
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int MAX = 10000;
int c[MAX],topo[MAX],t;
int n, m;//m表示关系数量,n代表有多少个任务
int G[MAX][MAX];//G[i][j] = 1 代表i任务要优先j任务完成
bool dfs(int u){
	c[u] = -1;//1代表已经访问过了,-1代表正在访问,0代表未访问
	for (int v = 0; v < n; v++) 
		if (G[u][v]) {
			if (c[v] < 0) {//存在有向环,失败退出
				return false;
			}
			else if (!c[v] && !dfs(v)) {
				return false;
			}
		}
	c[u] = 1;
	topo[--t] = u;//保存答案//注意因为dfs是递归实现的,所以遍历访问完一个节点后必须把它放在拓补序列的首部
	return true;
}
bool toposort(){
	t = n;
	
	for (int u = 0; u < n; u++) {
		if (!c[u]) {
			if (!dfs(u)) {
				return false;
			}
		}
	}
	return true;
}
int main() {
	int a, b;
	while (scanf("%d%d", &n, &m) == 2 && n ) {
		memset(G, 0, sizeof(G));
		
		for (int i = 0; i < m; i++) {
			scanf("%d%d", &a, &b);
			a--;//因为题意是从1开始的节点,所以存储进去的时候必须减一
			b--;
			G[a][b] = 1;
		}
		memset(c, 0, sizeof(c));
		if (toposort()) {//在拓补排序过程中将答案压入topo中
			for (int i = 0; i < n - 1; i++) 
				printf("%d ", topo[i] + 1);
			printf("%d\n", topo[n - 1] + 1);
		}
		else 
			printf("No\n");
		}
    return 0;
}

这里用到一个c数组。

c[u]=0表示从来没有访问过,(从来没有调用过dfs(u))。

c[u]=1表示已经访问过,并且还递归访问过他的所有子孙(即dfs(u)曾经被调用过,并已返回。

c[u]=-1表示正在被访问(即递归调用dfs(u)正在栈帧中,尚未返回)。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

deebcjrb

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值