#include <iostream>
#include <string>
#include <queue>
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; i<graph->nv; i++) {
for(int j=0; j<graph->nv; j++) {
graph->Graph[i][j] = 0;
}
}
for(int i=0; i<graph->ne; i++) {
int a, b;
cin >> a >> b;
graph->Graph[a][b] = 1; // 确定是下标从0开始
}
return graph;
}
vector<int> cal_indgree(G graph) {
// 记录每个节点的度
vector<int> ret;
for(int j=0; j<graph->nv; j++) {
// 改列和为0, 则说明该结点入度为0
int cnt = 0;
for(int i=0; i<graph->nv; i++) {
if(graph->Graph[i][j]==1) {
cnt++;
}
}
ret.push_back(cnt);
}
return ret;
}
void TopSort(G graph, vector<int>& indegree) {
queue<int> que; // 存储入度为0的节点
for(int i=0; i< graph->nv; i++) {
if(indegree[i]==0)
que.push(i);
}
vector<vector<int>> ans;
int cnt = 0;
while(!que.empty()) {
int tt = que.size();
vector<int> top;
for(int i=0; i<tt; i++) {
int tmp = que.front();
que.pop();
top.push_back(tmp);
cnt++;
// 断开tmp的后续节点的边
for(int j=0; j<graph->nv; 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<ans.size(); i++) {
for(int j=0; j<ans[i].size(); j++) {
cout << ans[i][j] + 1 << ' ';
}
cout << endl;
}
}
int main()
{
G graph = init_graph();
vector<int> 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
[Data structure] Topological sorting C++ implementation
Guess you like
Origin blog.csdn.net/ayitime/article/details/125587466
Recommended
Ranking