码迷,mamicode.com
首页 > 其他好文 > 详细

UVA10305 Ordering Tasks

时间:2016-05-31 01:08:27      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:

一个很裸的拓扑排序题目,只是因为很久没有复习toposort,所以拿来复习一下,最近几天要把图论的经典算法都复习一遍。

#include  <iostream>
#include  <cstdio>
#include  <cstring>
#include  <cstdlib>
#include  <vector>
#include  <queue>
#include  <algorithm>
#include  <cmath>
using namespace std;
const int maxn=105;
bool G[maxn][maxn];
int n,m,t,c[maxn],topo[maxn];
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;
}
void toposort()
{
	t=n;
	memset(c,0,sizeof(c));
	for(int u=1;u<=n;u++)
	{
		if(!c[u])
		{
			if(!dfs(u))
				return;
		}
	}
}
int main()
{
	while(scanf("%d%d",&n,&m))
	{
		memset(G,false,sizeof(G));
		if(n==0&&m==0)
			break;
		int u,v;
		for(int i=1;i<=m;i++)
		{
			scanf("%d%d",&u,&v);
			G[u][v]=true;
		}
		toposort();
		for(int i=1;i<=n-1;i++)
			printf("%d ",topo[i]);
		printf("%d\n",topo[n]);
	}
	return 0;
}

  

UVA10305 Ordering Tasks

标签:

原文地址:http://www.cnblogs.com/northsnow95/p/5544442.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!