定义:
对一个有向无环图(Directed Acyclic Graph简称DAG)G进行拓扑排序,是将G中所有顶点排成一个线性序列,使得图中任意一对顶点u和v,若边(u,v)∈E(G),则u在线性序列中出现在v之前。
代码如下:
//基于dfs的拓扑排序,复杂度O(v+e)
int sta[maxn],tp[maxn],num;
bool dfs(int u){
sta[u]=-1;
for(int v=0;v<n;v++){
if(gra[u][v]){
if(sta[v]<0){
return false;
}else if(!sta[v]&&!dfs(v)){
return false;
}
}
}
sta[u]=1;
tp[--num]=u;
}
bool tpsort(){
num=n;
memset(sta,0,sizeof(sta));
for(int u=0;u<n;u++){
if(!sta[u]){
if(!dfs(u)){
return false;
}
}
}
return true;
}
//基于bfs实现拓扑排序,复杂度O(v+e)
vector<int>gra[maxn];
int ind[maxn],tp[maxn];
void tpsort(){
queue<int>q;
for(int i=0;i<n;i++){
if(!ind[i]){
q.push(i);
}
}
int cnt=0;
while(!q.empty()){
int u=q.front();
q.pop();
tp[cnt++]=u;
int sz=gra[u].size();
for(int i=0;i<sz;i++){
int v=gra[u][i];
--ind[v];
if(!ind[v]){
q.push(v);
}
}
}
}