Uva(10305)

1386 ワード

これはトポロジーソートに関する問題であり、トポロジーシーケンスの1つを出力します.
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=150;
int c[maxn];
int topo[maxn],t;
int G[maxn][maxn];
int n,m;
bool dfs(int u)
{
	c[u]=-1;
	for(int v=1;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;
	return true;
} 
//   c          ,  c[u]=0      ,c[u]=-1      ,c[u]=1                  
bool toposort()
{
	t=n;
	memset(c,0,sizeof(c));
	for(int u=1;u<=n;u++)
	{
		if(!c[u])
		{
			if(!dfs(u))
			return false;
		}
	}
	return true;
}
int main()
{
	while(scanf("%d %d",&n,&m)!=EOF)
	{
		if(n==0&&m==0)
		break;
		memset(G,0,sizeof(G));
		memset(topo,0,sizeof(topo));
		int u,v;
		for(int i=0;i<m;i++)
		{
			scanf("%d %d",&u,&v);
			G[u][v]=1;
		}
		toposort();
		for(int i=0;i<n-1;i++)
		printf("%d ",topo[i]);
		printf("%d
",topo[n-1]); } return 0; }