拓扑排序模板

bool dfs(int u)
{
	vis[u] = -1;
	REP(i, 0, g[u].size())
	{
		int v = g[u][i];
		if(vis[v] == -1) return false;
		else if(!vis[v]) dfs(v); 
	}	
	vis[u] = 1; ans[--t] = u; //注意这里倒序加入
	return true;
}

bool toposort() //可以用来判断有向图是否有环return false 则有环
{
	t = n;
	memset(vis, 0, sizeof(vis));
	REP(i, 0, n)
		if(!vis[i] && !dfs(i))
			return false;
	return true;
}


裸题:UVa 10305

#include<cstdio>
#include<vector>
#include<cstring>
#define REP(i, a, b) for(int i = (a); i < (b); i++)
using namespace std;

const int MAXN = 1123;
vector<int> g[MAXN];
int vis[MAXN], ans[MAXN], n, m, t;

bool dfs(int u)
{
	vis[u] = -1;
	REP(i, 0, g[u].size())
	{
		int v = g[u][i];
		if(vis[v] == -1) return false;
		else if(!vis[v]) dfs(v); 
	}	
	vis[u] = 1; ans[--t] = u;
	return true;
}

bool toposort()
{
	t = n;
	memset(vis, 0, sizeof(vis));
	REP(i, 0, n)
		if(!vis[i] && !dfs(i))
			return false;
	return true;
}

int main()
{
	while(~scanf("%d%d", &n, &m) && n)
	{
		REP(i, 0, n) g[i].clear();
		while(m--)
		{
			int u, v;
			scanf("%d%d", &u, &v);
			u--; v--;
			g[u].push_back(v);
		}
		
		if(toposort())
		{
			REP(i, 0, n - 1) printf("%d ", ans[i] + 1);
			printf("%d\n", ans[n - 1] + 1);
		}
		else puts("NO");
	}
	
	return 0;	
} 

 

posted @ 2018-06-18 10:08  Sugewud  阅读(125)  评论(0编辑  收藏  举报