有向无环图(Directed Acyclic Graph,简称DAG)的拓扑排序,
简单化来讲,把有向图比作按顺序做事,拓扑排序就是输出做事的顺序
算法过程:
1> 找入度为0的点访问输出,断其出边
2> 重复1,没有入度为0的点时结束
#include <iostream>
using namespace std;
int n, m, num; //num记录访问过的点的个数
int a[2001][2001]; //邻接矩阵
int In[2001]; //记录每个点的入度
int In_zero() { //找图中入度为0的点返回
for(int i=1; i<=n; i++) if(In[i] == 0) return i;
return 0; //没有找到
}
void topology() {
int x = In_zero();
if(x == 0) return;
cout << x << " -> ";
In[x] = -1; //不需要标记数组,直接使入度=-1
num ++;
for(int i=1; i<=n; i++) {
if(a[x][i] == 1) {
In[i] --; //断x的出边
//a[x][i] = 0;
}
}
topology();
}
void build_graph() {
int x, y;
cin >> n >> m;
for(int i=1; i<=m; i++) {
cin >> x >> y;
a[x][y] = 1;
In[y] ++;
}
}
int main() {
build_graph();
topology();
if(num < n) cout << "Is not DAG!" << endl; //图中有环
cout << endl << num << endl;
return 0;
}
随意举个栗子:
测试数据:
6 5
5 2
5 4
1 3
1 6
2 1
上图的拓扑排序结果:5 2 1 3 4 6
###