toposort算法模板

来源:互联网 发布:程序员有前途吗 编辑:程序博客网 时间:2024/05/01 16:05
//队列实现/*复杂度:O(|V|+|E|)输入: n 全局变量 表示点数       g 全局变量 g[i]表示从点i连出去的边输出:返回对给定的图,是否可以拓扑排序       topo 全局变量,拓扑排序的结果*/const int maxn = 100000+5;vector<int> g[maxn];//邻接矩阵作用int n,m,topo[maxn];int indegree[maxn];//入度bool toposort(){    memset(indegree,0,sizeof(indegree));    for(int i = 0; i < n; ++i)        for(int j = 0; j < g[i].size(); ++j)        indegree[g[i][j]]++;    int tot = 0;    queue<int> q;    for(int i = 0; i < n; ++i)        if(!indegree[i]) q.push(i);    while(!q.empty())    {        int x = q.front(); q.pop();        topo[tot++] = x;        for(int j = 0; j < g[x].size(); ++j)        {            int t = g[x][j];            indegree[t]--;            if(!indegree[t]) q.push(t);        }    }    if(tot == n) return true;    else return false;}//DFS递归实现,from刘汝佳《算法竞赛入门经典II》int c[maxn];int topo[maxn],t;bool dfs(int u){    c[u] = -1;//-1表示正在访问,还未返回    for(int v = 0; v < n; ++v) if(G[u][v])    {        if(c[v] < 0) return false;        else if(!c[v] && !dfs(v)) return false;    }    c[u] = 1;//访问结束且已返回,1代表访问过    topo[--t] = u;    return true;}bool toposort(){    t = n;    memset(c,0,sizeof(c));    for(int u = 0; u < n; ++u) if(!c[u])        if(!dfs(u)) return false;    return true;}

0 0