输入:一个有向图
输出:顶点的拓扑序列
具体流程:
(1) 将所有入度为0的点加入队列
(2) 每次取出队首顶点
(3) 删除其连出的边,检查是否有新的入度为0的顶点,有则加入队列
(4) 重复(2)直到队列为空
样例输入
5 5
0 1 1
0 2 1
1 2 1
2 3 1
4 2 1
样例输出
0 4 1 2 3
#include <iostream>
#include <queue>
using namespace std;
int ** edges;
int * in_degrees;
int * out_degrees;
int v,e;
void topSort(){
queue<int> q;
for(int i=0;i<v;i++){
if(0 == in_degrees[i]){
q.push(i);
}
}
while(!q.empty()){
int front = q.front();
q.pop();
printf("%d ",front);
for(int j=0;j<v;j++){
if(edges[front][j]!=0){
edges[front][j] = 0;
in_degrees[j]--;
if(0 == in_degrees[j]){
q.push(j);
}
}
}
}
}
int main(void){
cin>>v>>e;
//init
edges = new int*[v];
in_degrees = new int[v];
out_degrees = new int[v];
memset(in_degrees,0,v*sizeof(int));
memset(out_degrees,0,v*sizeof(int));
int i;
for(i=0;i<v;i++){
edges[i] = new int[v];
memset(edges[i],0,v*sizeof(int));
}
//input
for(i=0;i<e;i++){
int a,b,w;
cin>>a>>b>>w;
edges[a][b] = w; //从a到b有一条路
in_degrees[b]++; //b的入度加1
out_degrees[a]++; //a的出度加1
}
topSort();
//huishou
for(i=0;i<v;i++){
delete edges[i];
}
delete edges;
delete in_degrees;
delete out_degrees;
return 0;
}