UVA10305OrderingTasks

本文提供了一种解决UVA10305问题的算法实现,该问题涉及任务间的依赖关系排序。通过使用深度优先搜索(DFS)来检测是否存在环,并完成拓扑排序,确保所有任务按照正确的顺序执行。
//UVA10305OrderingTasks
#include<cstdio>
#include<cstdlib>
#include<cstring>
//#define LOCAL
const int MAXN = 100 + 10;
char pre[MAXN][MAXN];
char topo_series[MAXN];
int m ,n;
int tag[MAXN];//标记访问状态 
int now = 0;
void read() {
	int x, y;
	for(int i = 0; i < m; i++) {
		scanf("%d%d", &x, &y);
		pre[y][x] = 1;
	}
}

bool DFS(int node) {
	tag[node] = -1;//开始调用函数的标志 
	for(int i = 1; i <= n; i++) {
		if(pre[node][i]) {//有比node优先级低的 
			if(tag[i] < 0) {printf("node = %d, i = %d", node, i); return false;}//有环存在 
			if(!tag[i] && !DFS(i)) {printf("node = %d, i = %d", node, i);  return false;}//若未被访问,则进行访问,若出现错误,则返回false 
		}
	}
	//printf("now = %d, node = %d\n", now, node);
	topo_series[now++] = node;//优先级最后的存在最后 
	tag[node] = 1;//函数调用结束的标志 
	return true;
}
bool topo() {
	for(int i = 1; i <= n; i++) {
		if(!tag[i]) //未被访问过 
		    if(!DFS(i)) return false;
	}
	return true;
}

int main() {
	#ifdef LOCAL
	freopen("UVA10305in.txt", "r", stdin);
	freopen("UVA10305out.txt", "w", stdout);
	#endif
	while((scanf("%d%d", &n, &m)) == 2 && n) {
		memset(topo_series, 0, sizeof(topo_series));
		memset(tag, 0, sizeof(tag)); 
		memset(pre, 0, sizeof(pre));
		read();
	    now = 1;//now标记当前存储位置的指向 
		if(!topo()) printf("ERROR\n");	
		for(int i = 1; i <= n; i++) {
			if(i - 1) printf(" ");
			printf("%d", topo_series[i]);
		}
		printf("\n");
	}
	return 0;
} 
/*
5 4
1 2
2 3
1 3
1 5
2 1
1 2
2 1
2 1
0 0
0 0
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值