Ordering Tasks(拓扑排序+dfs)

Ordering Tasks

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个任务要做, 不幸的是,这些任务并不是独立的,执行某个任务之前要先执行完其他相关联的任务

题解:拓扑排序模版题;

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<queue>
using namespace std;
#define mem(x,y) memset(x,y,sizeof(x))
#define SI(x) scanf("%d",&x)
#define PI(x) printf("%d",x)
#define P_ printf(" ")
const int INF=0x3f3f3f3f;
typedef long long LL;
const int MAXN=110;
int que[MAXN];
int mp[MAXN][MAXN];
int n;
int vis[MAXN];
int ans[MAXN];
void topu(){
		int k=0,a;
		mem(vis,0);
		while(k<n){
			int temp=INF;
			for(int i=1;i<=n;i++){
				if(!vis[i]&&que[i]==0){
					ans[k++]=i;temp=i;
					break;
				}
			}
			if(temp==INF)break;
			vis[temp]=1;
			for(int i=1;i<=n;i++)if(mp[i][temp]){
				que[i]--;
				
			}
		}
		for(int i=0;i<k;i++){
			if(i)P_;
			PI(ans[i]);
		}
		puts("");
}
int main(){
	int m,a,b;
	while(scanf("%d%d",&n,&m),n|m){
		mem(que,0);
		mem(mp,0);
		while(m--){
			SI(a);SI(b);
			que[b]++;
			mp[b][a]=1;
		}
		topu();
	}
	return 0;
}

  dfs也可以写拓扑排序:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<queue>
using namespace std;
#define mem(x,y) memset(x,y,sizeof(x))
#define SI(x) scanf("%d",&x)
#define PI(x) printf("%d",x)
#define P_ printf(" ")
const int INF=0x3f3f3f3f;
typedef long long LL;
const int MAXN=110;
int mp[MAXN][MAXN];
int vis[MAXN],ans[MAXN];
int n;
int k;
bool dfs(int u){
	vis[u]=-1;
	for(int i=1;i<=n;i++){
		if(mp[u][i]){
			if(vis[i]==-1)return false;//表示结点v正在访问中,(即调用dfs(u)还在栈中,尚未返回)
			if(!vis[i])dfs(i);
		}
	}
	ans[--k]=u;
	vis[u]=1;
	return true;
}
bool topu(){
	mem(vis,0);
	k=n;
	for(int i=1;i<=n;i++){
		if(!vis[i])if(!dfs(i))
		return false;
	}
	for(int i=0;i<n;i++){
		if(i)P_;
		PI(ans[i]);
	}
	puts("");
	return true;
}
int main(){
	int m,a,b;
	while(scanf("%d%d",&n,&m),n|m){
		mem(mp,0);
		while(m--){
			SI(a);SI(b);
			mp[a][b]=1;
		}
		topu();
	}
	return 0;
}

  

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值