#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
*/
拓扑排序
最新推荐文章于 2021-12-03 21:41:37 发布