UVA 10305 Ordering Tasks

欧拉回路:每个节点走到最深再倒序输出

#include<iostream>
#include<vector>
#include<queue>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=100+5;
int G[maxn][maxn],topo[maxn];
int c[maxn],m,t; //保存状态; 
bool dfs(int u)
{
	c[u]=-1;
	for(int v=1;v<=m;v++)
	if(G[u][v]) 
	if(c[v]<0) return false;
	else if(!c[v]) if(!dfs(v)) return false; //未走遍走,若存在有向环就结束 
	c[u]=1;topo[--t]=u;
	return true;
}
bool toposort()
{
	t=m;
	memset(c,0,sizeof(c));
	memset(topo,0,sizeof(topo));
	for(int u=1;u<=m;u++)
	if(!c[u]&&!dfs(u)) return false;  //存在有向环;
	return true; 
}
int main()
{
	int n;
	while(scanf("%d%d",&m,&n)&&m)
	{
		memset(G,0,sizeof(G));
		for(int i=0;i<n;i++)
		{
			int x,y;
			cin>>x>>y;
			G[x][y]=1;
		}
		if(toposort())
		for(int i=0;i<m;i++)
		{
			if(i) putchar(' ');
			printf("%d",topo[i]);
		}
		putchar('\n');
	}
	return 0;
}


你可能感兴趣的:(UVA 10305 Ordering Tasks)