Uva10305(有向图拓扑排序dfs

#include<bits/stdc++.h>
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; //第一个判断v是否被搜索过
        }
    }
    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]==0){
            if(dfs(u)==false) 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;
}

猜你喜欢

转载自blog.csdn.net/weixin_43413621/article/details/88383753