码迷,mamicode.com
首页 > 编程语言 > 详细

UVa 10305 - Ordering Tasks (拓扑排序裸题)

时间:2018-03-08 00:17:44      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:instance   pen   bre   include   res   else   ble   判断   body   

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 <= 100 and 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 with n = 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
思路:
拓扑排序裸题,用的是紫书上dfs的写法

实现代码:
#include<bits/stdc++.h>
using namespace std;
const int M = 200;
int x,y,n,m,vis[M],topo[M],g[M][M],t;
bool dfs(int u){
    vis[u] = -1;  //当前在判断的
    for(int i = 1;i <= n;i ++){
        if(g[u][i]){
        if(vis[i] < 0) return false;
        if(!vis[i]&&!dfs(i)) return false;
        }
    }
    vis[u] = 1; topo[t--] = u;
    return true;
}

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

int main()
{
    while(cin>>n>>m){
        if(n==0&&m==0) break;
        memset(g,0,sizeof(g));
        while(m--){
            cin>>x>>y;
            g[x][y] = 1;
        }
        if(toposort()){
            for(int i = 1;i <= n;i ++){
                if(i==n) cout<<topo[i]<<endl;
                else cout<<topo[i]<<" ";
            }
        }
    }
    return 0;
}

 

UVa 10305 - Ordering Tasks (拓扑排序裸题)

标签:instance   pen   bre   include   res   else   ble   判断   body   

原文地址:https://www.cnblogs.com/kls123/p/8525607.html

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