拓扑排序

来源:互联网 发布:二维码标签机打印软件 编辑:程序博客网 时间:2024/06/06 03:00

拓扑排序的两种方法

利用入度来排序(Kahn)

时间复杂度:O(E+V)
伪代码:

L ← Empty list that will contain the sorted elementsS ← Set of all nodes with no incoming edgeswhile S is non-empty do    remove a node n from S    add n to tail of L    for each node m with an edge e from n to m do        remove edge e from the graph        if m has no other incoming edges then            insert m into Sif graph has edges then    return error (graph has at least one cycle)else    return L (a topologically sorted order)

c++代码:

const int MAX_E = 1000;const int MAX_N = 1000;struct Edge{    int a, b;};Edge edge[MAX_E];//边int in[MAX_N];//记录入度vector<int> vec[MAX_N];//记录每个顶点相邻的点int edgecnt, N;//拓扑排序void TopoSort(){    queue<int> q;    for( int i = 0; i < N; i++ ){        if( !in[i] ){            q.push( i );        }    }    vector<int> ans;    while( !q.empty() ){        int t = q.front();        q.pop();        ans.push_back( t );        for( int i = 0; i < vec[t].size(); i++ ){            in[vec[t][i]]--;            if( in[vec[t][i]] == 0 ){                q.push( vec[t][i] );            }        }    }    //打印答案    for( int i = 0; i < ans.size(); i++ ){        cout << ans[i] << " ";    }    cout << endl;}int main(){    cin >> N >> edgecnt;    for( int i = 0; i < N; i++ ){        vec[i].clear();        in[i] = 0;    }    for( int i = 0; i < edgecnt; i++ ){        cin >> edge[i].a >> edge[i].b;        vec[edge[i].a].push_back( edge[i].b );        in[edge[i].b]++;    }    TopoSort();    return 0;}

利用深搜来排序

时间复杂度:O(E+V)
伪代码:

L ← Empty list that will contain the sorted nodeswhile there are unmarked nodes do    select an unmarked node n    visit(n) function visit(node n)    if n has a temporary mark then stop (not a DAG)    if n is not marked (i.e. has not been visited yet) then        mark n temporarily        for each node m with an edge from n to m do            visit(m)        mark n permanently        unmark n temporarily//这个变量可以用来在排序的过程中检测是否有环,因为检测是否有环也是用DFS        add n to head of L

c++代码:

不想写了。。。伪代码已经很清楚了。。。
0 0
原创粉丝点击