UVa 10305 - Ordering Tasks 拓扑排序

Problem F

Ordering Tasks

Input: standard input

Output: standard output

Time Limit: 1 second

Memory Limit: 32 MB

 

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 <= 100and mn 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 withn = 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

(The Joint Effort Contest, Problem setter: Rodrigo Malta Schmidt)


#include <iostream>
#include <cstring>
#include <cstdio>
#include <stack>
using namespace std;

const int MAX = 100+5;

int g[MAX][MAX], vis[MAX];
int n, m;
stack<int> s;

bool dfs(int u)
{
	vis[u]=-1;
	for(int v=1; v <= n; v++)
	{
		if(g[u][v])
		{
			if(vis[v]<0) return false; // 在栈中即表示有环 
			else if(!vis[v] && !dfs(v)) return false;
		}
	}
	vis[u]=1;
	s.push(u);
	return true;
}

bool topoSort()
{
	int count=0;
	for(int i=1; i <= n; i++)
	{
		if(!vis[i])
		{
			if(!dfs(i))
				return false;
		}
	}
	return true;
}

void init()
{
	while(!s.empty())
		s.pop();
	memset(g, 0, sizeof(g));
	memset(vis, 0, sizeof(vis));
}

int main()
{
//	freopen("in.txt","r",stdin);
	while(cin>>n>>m)
	{
		if(m==0 && n==0)
			break;
			
		init();
		int u, v;
		for(int i=0; i < m; i++)
		{
			cin>>u>>v;
			g[u][v]=1;
		}
		if(topoSort())
		{
			while(!s.empty())
			{
				cout << s.top() << " ";
				s.pop();
			}
			cout << endl;
		}
	}
	return 0;
}


你可能感兴趣的:(C++,算法,栈,图,uva)