首页 > 代码库 > 图——拓扑排序(uva10305)

图——拓扑排序(uva10305)

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 m. n 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递归实现来遍历

 

自己敲的时候,wa了n次...然后Baidu了一下,发现自己的错误和网友的错误惊人的相似(QAQ),判断m n是否为0的时候应该用 m||n 来确定两个都为0而不是 m&&n !!

#include<iostream>
#include<string.h>
#include<cstdio>
using namespace std;
const int maxn = 1000 + 5;

int a[maxn][maxn];
int c[maxn];
int topo[maxn];
int n, m, t;

bool dfs(int u){
    c[u] = -1;
    for(int v=1; v<=n; v++){
        if(a[u][v]){
            if(c[v] < 0) return false;
            else if(!c[v] && !dfs(v)) return false;
        }
    }
    c[u] = 1;
    topo[--t] = u;
    return true;
}
bool topo_sort(){
    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(){
    int j, k;
    while(scanf("%d %d", &n, &m) == 2 && (n || m )){
        memset(a, 0, sizeof(a));
        for(int i=0; i<m; i++){
            cin >> j >> k;
            a[j][k] = 1;
        }
        if(topo_sort()){
            for(int i=0; i<n; i++){
                if(i == 0) cout << topo[i];
                else cout << " " << topo[i];
            }
            cout << endl;    
        }
        else
            cout << "No" << endl;

    }

    
    return 0;
}

 

图——拓扑排序(uva10305)