拓扑排序
AOV(Activity On Vertex network)网:
活动在顶点上的网,是一种顶点表示活动,边表示先后顺序的有向无环图,可以用来表示产品生产流等。
拓扑排序:
将有向无环图的所有顶点排列成一个序列,序列中的顶点满若一对顶点u和v存在路径u->v,则u一定出现再v之前。
图解:
略…有时间再补充吧
步骤:
- 1)从有向图里找一个没有前驱节点的顶点输出;
- 2)删除1)中顶点,并删除该顶点作为前驱节点的全部边;
- 3)重复1)和2)直到剩余的网中不存在无前驱节点的顶点;
代码:
- 拓扑排序-邻接矩阵版本
#include<bits/stdc++.h>
using namespace std;
const int maxn = 10010;
vector<vector<int> >G(maxn, vector<int>(maxn,0));
vector<int>indegree(maxn,0);
vector<int> topologic(vector<vector<int> >G, vector<int>indegree, int n){
vector<int> res;
queue<int>q;
for(int i=0; i<n; ++i){
if(indegree[i] == 0)
q.push(i);
}
while(!q.empty()){
int cur = q.front();
q.pop();
res.push_back(cur);
for(int i=0; i<n; ++i){
if(G[cur][i] != 0){
G[cur][i] = 0;
indegree[i]--;
if(indegree[i] == 0)
q.push(i);
}
}
}
return res;
}
int main(){
int n;
cin>>n;
for(int i=0;i<n;++i){
for(int j=0; j<n; ++j){
int now;
cin>>now;
G[i][j] = now;
if(now)
indegree[j]++;
}
}
for(int i=0;i<n; ++i)
cout<<indegree[i]<<" "<<endl;
vector<int> res;
res = topologic(G, indegree, n);
for(int i=0; i<res.size(); ++i)
cout<<res[i]+1<<" ";
return 0;
}
/*
4
0 1 1 0
0 0 0 1
0 1 0 1
0 0 0 0
*/
- 拓扑排序-邻接表版本
略...有时间再补充