拓扑排序 基于DFS

来源:互联网 发布:jsp项目源码 编辑:程序博客网 时间:2024/05/04 10:04
#include <iostream>
#include <bits/stdc++.h>
using namespace std;

const int Max = 1001;
int M[Max][Max], vis[Max], topo[Max], pos;
int n, m;

bool DFS(int u)
{
    vis[u] = -1;
    for(int v = 1; v <= n; v++)
    {
        if(M[u][v])
        {
            if(vis[v] == -1) return false;
            else if(!vis[v] && !DFS(v)) return false;
        }
    }
    vis[u] = 1;
    topo[pos--] = u;
    return true;
}

bool toposort()
{
    pos = n;
    memset(vis, 0, sizeof(vis));
    for(int u = 1; u <= n; u++)
    {
       if(!vis[u]){
        if(!DFS(u)) return false;
       }
    }
    return true;
}

int main()
{
    //freopen("in.txt", "r", stdin);
    while(cin >> n >> m && n)
    {
        memset(M, 0, sizeof(M));
        memset(vis, 0, sizeof(vis));
        int x, y;
        pos = n;
        for(int i = 1; i <= m; i++)
        {
            cin >> x >> y;
            M[x][y] = 1;
        }
        toposort();
        for(int i = 1; i <= n; i++)
        {
            if(i != 1) cout << " ";
            cout << topo[i];
        }
        cout << endl;
    }
    return 0;

}

大神: http://blog.csdn.net/lisonglisonglisong/article/details/45543451