图的拓补排序基本算法

拓补排序很简单,就是一个图中存在(u, v)使得u必须在v之前遍历,而算法所要做的就是按照拓补顺序将图遍历。举例子,就像大学课程,某课程a是课程b的先修课程,即必须先学完a才能学b课程,而用拓补算法能够合理给出一个课程安排顺序。注意图中不能存在环,否则拓补排序将失败。基本算法如下:

#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
#include <cstring>

using namespace std;
const int maxn = 100 + 5;

int n, m;
int G[maxn][maxn], inDgree[maxn];
vector<int> ans;

bool topoSort() {
    queue<int> q;
    int cnt = 0;

    for(int i = 0; i < n; i++)
        if(inDgree[i] == 0)     q.push(i);  //将所有节点为0的点压入队列

    while(!q.empty()) {
        int u = q.front();  q.pop();
        ans.push_back(u);
        cnt++;
        for(int i = 0; i < n; i++)
            if(G[u][i]) {
                G[u][i] = 0;
                if(--inDgree[i] == 0)   q.push(i);
            }

    }

    if(cnt != n)    return false;
    else              return true;
}

int main()
{
    //freopen("input.txt", "r", stdin);
    cin >> n >>m;
    memset(G, 0, sizeof(G));
    memset(inDgree, 0, sizeof(inDgree));

    int u, v;
    for(int i = 0; i < m; i++) {
        cin >> u >> v;
        G[u][v] = 1;      inDgree[v]++;
    }

    ans.clear();
    if(topoSort()) {
        printf("%d", ans[0]);
        for(int i = 1; i < ans.size(); i++)     printf("-->%d", ans[i]);
        printf("\n");
    }
    else    printf("Error ! there is a circle in the graph!!");



    return 0;
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值