zoukankan      html  css  js  c++  java
  • 拓扑排序

    定义:

    对一个有向无环图(Directed Acyclic Graph简称DAG)G进行拓扑排序,是将G中所有顶点排成一个线性序列,使得图中任意一对顶点u和v,若边(u,v)∈E(G),则u在线性序列中出现在v之前。 

    代码如下:

    //基于dfs的拓扑排序,复杂度O(v+e)
    int sta[maxn],tp[maxn],num;
    bool dfs(int u){
        sta[u]=-1;
        for(int v=0;v<n;v++){
            if(gra[u][v]){
                if(sta[v]<0){
                    return false;
                }else if(!sta[v]&&!dfs(v)){
                    return false;
                }
            }
        }
        sta[u]=1;
        tp[--num]=u;
    }
    bool tpsort(){
        num=n;
        memset(sta,0,sizeof(sta));
        for(int u=0;u<n;u++){
            if(!sta[u]){
                if(!dfs(u)){
                    return false;
                }
            }
        }
        return true;
    }
    //基于bfs实现拓扑排序,复杂度O(v+e)
    vector<int>gra[maxn];
    int ind[maxn],tp[maxn];
    void tpsort(){
        queue<int>q;
        for(int i=0;i<n;i++){
            if(!ind[i]){
                q.push(i);
            }
        }
        int cnt=0;
        while(!q.empty()){
            int u=q.front();
            q.pop();
            tp[cnt++]=u;
            int sz=gra[u].size();
            for(int i=0;i<sz;i++){
                int v=gra[u][i];
                --ind[v];
                if(!ind[v]){
                    q.push(v);
                }
            }
        }
    }
    

      

  • 相关阅读:
    type() & dir()

    手机操作API
    APP模拟手势高级操作
    APP元素事件操作API
    APP元素信息操作API
    APP元素定位操作
    手机控件查看工具uiautomatorviewer
    App基础操作API
    Appium入门
  • 原文地址:https://www.cnblogs.com/imzscilovecode/p/8656810.html
Copyright © 2011-2022 走看看