拓扑排序

#include <iostream>
#include <climits> // for INT_MAX
#include <stack>
using namespace std;
/** 顶点数的最大值*/
const int MAX_NV = 100;
/** 边的权值,对无权图,用0 或1 表示是否相邻;对有权图,则为权值. */
typedef int graph_weight_t;
const graph_weight_t GRAPH_INF = INT_MAX;
/**
*@struct
*@brief 邻接矩阵.
*/
struct graph_t {
    int nv; // 顶点数
    int ne; // 边数
    // 邻接矩阵,存放边的信息,如权重等
    graph_weight_t matrix[MAX_NV][MAX_NV];
};
graph_t g;
/** 拓扑排序的结果. */
int topological[MAX_NV];

/*
* @brief 拓扑排序.
* @param[in] g 图对象的指针
* @param[out] topological 保存拓扑排序的结果
* @return 无环返回true,有环返回false
*/
bool topo_sort(const graph_t &g, int topological[]) {
    const int n = g.nv;
    int *in_degree = new int[n](); // in_degree[i] 是顶点i 的入度
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (g.matrix[i][j] < GRAPH_INF)
                in_degree[j]++;
        }
    }
    stack<int> s;
    for(int i = 0; i < n; i ++) {
        if(in_degree[i] == 0)
            s.push(i);
    }
    int count = 0; /* 拓扑序列的元素个数*/
    while(!s.empty()) {
        const int u = s.top(); s.pop();
        topological[count++] = u;
        for (int i = 0; i < n; i++) if (g.matrix[u][i] < GRAPH_INF) {
            if(--in_degree[i] == 0) s.push(i);
        }
    }
    delete[] in_degree;
    if(count != n) { /* 有环*/
        return false;
    } else { /* 无环*/
        return true;
    }
}

/** 读取输入,构建图. */
void read_graph() {
    /* 读取节点和边的数目*/
    cin >> g.nv >> g.ne;
    /* 初始化图,所有节点间距离为无穷大*/
    for (int i = 0; i < g.nv; i++) {
        for (int j = 0; j < g.nv; j++) {
            g.matrix[i][j] = GRAPH_INF;
        }
    }
    /* 读取边信息*/
    for (int k = 0; k < g.ne; k++) {
        char chx, chy;
        graph_weight_t w;
        cin >> chx >> chy >> w;
        g.matrix[chx - 'A'][chy - 'A'] = w;
    }
}

int main() {
    read_graph();
    /* 拓扑排序*/
    topo_sort(g, topological);
    for (int i = 0; i < g.nv; i++) {
        cout << (char)('A' + topological[i]) << " ";
    }
    return 0;
}

/* test
输入数据:
6 8
A C 10
A E 30
A F 100
B C 5
C D 50
D 5 10
E D 20
E F 60
输出:
B A E F C D
*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值