栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

【数据结构】拓扑排序C++实现

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【数据结构】拓扑排序C++实现

#include 
#include 
#include 
using namespace std;
#define max_nv 100

typedef struct g* G;
struct g{
    int nv;     // 顶点数
    int ne;
    int Graph[max_nv][max_nv];
};

G init_graph() {
    G graph = new g;
    cin >> graph->nv;
    cin >> graph->ne;
    
    // 初始化
    for(int i=0; inv; i++) {
        for(int j=0; jnv; j++) {
            graph->Graph[i][j] = 0;
        }
    }

    for(int i=0; ine; i++) {
        int a, b;
        cin >> a >> b;
        graph->Graph[a][b] = 1;     //  确定是下标从0开始
    }

    return graph;
}

vector cal_indgree(G graph) {
    // 记录每个节点的度
    vector ret;
    for(int j=0; jnv; j++) {            // 改列和为0, 则说明该结点入度为0
        int cnt = 0;
        for(int i=0; inv; i++) {
            if(graph->Graph[i][j]==1) {
                cnt++;
            }
        }
        ret.push_back(cnt);
    }

    return ret;
}

void TopSort(G graph, vector& indegree) {
    queue que;     // 存储入度为0的节点
    for(int i=0; i< graph->nv; i++) {
        if(indegree[i]==0)
            que.push(i);
    }

    vector> ans;
    int cnt = 0;
    while(!que.empty()) {
        int tt = que.size();
        vector top;
        for(int i=0; i
            int tmp = que.front();
            que.pop();

            top.push_back(tmp);
            cnt++;

            // 断开tmp的后续节点的边
            for(int j=0; jnv; j++) {
                if(graph->Graph[tmp][j] == 1) {
                    indegree[j]--;
                    if(indegree[j]==0)
                        que.push(j);
                }
            }
        }
        ans.push_back(top);
    }

    if(cnt != graph->nv)
        cout << "loop is in the graph" << endl;

    for(int i=0; i
        for(int j=0; j
            cout << ans[i][j] + 1 << ' ';
        }
        cout << endl;
    }

}


int main()
{
    G graph = init_graph();
    vector indegree = cal_indgree(graph);
    TopSort(graph, indegree);


    return 0;
}


// 测试用例
//5 6
//4 0
//0 1
//0 2
//1 3
//2 1
//2 4
// 0 2 1 3 4

// ZJU 陈越姥姥例子
// 15 14
// 0 2
// 1 2
// 3 4
// 4 5
// 2 6
// 7 8
// 6 9
// 8 9
// 6 10
// 8 10
// 6 11
// 1 12
// 9 13
// 5 14
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1000868.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号