对一个有向图的节点进行拓扑排序,可以用来判断该有向图是否成环,有环则无拓扑序列,无环则有。
#include <cstdio>
#include <cstring>
#include<iostream>
#include <queue>
using namespace std;
const int maxn = 1e5 + 7;
int n,m, du[maxn], head[maxn], tot,cnt,ans[maxn];
struct node {
int v, next;
} edge[maxn];
queue<int>q;
void add(int u, int v) {
edge[tot].v = v;
edge[tot].next = head[u];
head[u] = tot++;
}
void init() {
tot = 0;
memset(du, 0, sizeof(du));
memset(head, -1, sizeof(head));
}
void solve() {
while(!q.empty()) {
int u = q.front();
q.pop();
ans[cnt++]=u;
for (int i = head[u] ; i != -1 ; i = edge[i].next) {
du[edge[i].v]--;
if (!du[edge[i].v]) q.push(edge[i].v);
}
}
}
int main() {
int x,y;
scanf("%d",&n);
init();
for (int i = 1 ; i <= n ; i++) {
while(scanf("%d",&x)!=EOF&&x!=0){
add(i,x);
du[x]++;}
}
for (int i = 1 ; i <= n ; i++)
if (!du[i]) q.push(i);
solve();
if(cnt==m)
{
for(int i=0;i<cnt;i++)
cout<<ans[i]<<" ";
cout<<endl;
}
else
cout<<"有向图成环"<<endl;
return 0;
}