拓扑排序练习:给任务排序(UVA10305)

本文介绍了一种使用深度优先搜索(DFS)实现拓扑排序的方法,以解决任务依赖关系问题。通过构建图并采用递归方式遍历节点,确保所有任务能够按照正确的顺序被执行。

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

解题思路:利用vectior存储输入的拓扑关系,定义数组记录每一个点状态。对状态显示还未被遍历的点进行DFS(),遍历该点以及与该点有直接拓扑关系的点。在DFS过程中将元素压入存放拓扑结果的vector结构ans。具体分析下面给出的程序。

大体题意:

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

 

题意:就是给你几组任务,给出了任务的先后顺序,求出他们的执行顺序

拓扑排序就是用来解决这类排序问题的... 先构造出一个图,用dfs递归实现来遍历

#include<cstdio>
#include<string>
#include<vector>
#include<string.h>
#include<iostream>
using namespace std;

vector<int> a[100];
int mark[100];   //mark为1表示已经遍历该节点及其子节点
                 //为0表示还未遍历,为-1表示正在遍历
vector<int> topo; 

bool DFS(int u)
{
	mark[u]=-1;
	for(int i=0;i<a[u].size();i++)
	{
		if(mark[a[u][i]]==-1)   //再次遇到正在遍历中的,返回false 
		{
			return false;
		}
		else if(mark[a[u][i]]==0&&DFS(a[u][i])==false)    //未遍历则开始遍历并对返回值做出判断 
		return false;
	}
	mark[u]=1;              //该值遍历完成 
	topo.push_back(u);     //放入topo序列中 
	return true;
}

int main()
{
	int n,m;
	while(cin>>n>>m)
	{
		if(n==0&&m==0)
		break; 
		memset(mark,0,sizeof(mark));
	    for(int i=1;i<=n;i++)
	    {
	    	a[i].clear();   //清空一定不能忘 
		}
		topo.clear();       //清空 
		for(int i=1;i<=m;i++)
		{
			int u,v;
			cin>>u>>v;
			a[u].push_back(v); 
		}
		bool flag=true;
		for(int i=1;i<=n;i++)
		{
			if(mark[i]==1) continue;   //已经遍历过,直接跳 
			if(DFS(i)==false)       //有一个false即不存在 
			{
				flag=false;
			}
		}
		if(flag==true)
		{
			for(int i=topo.size()-1;i>=0;i--)     //拓扑排序从后往前打印 
			{
				cout<<topo[i]<<" ";
			}
			cout<<endl;
		}
		else
		cout<<"not exist."<<endl;
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值