拓扑排序

来源:互联网 发布:化妆水评测 知乎 编辑:程序博客网 时间:2024/05/15 03:42
#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 8A C 10A E 30A F 100B C 5C D 50D 5 10E D 20E F 60输出:B A E F C D*/

0 0
原创粉丝点击