拓扑排序的方法如下:
(1)从有向图中选择一个没有前驱(即入度为0)的顶点并且输出它.
(2)从网中删去该顶点,并且删去从该顶点发出的全部有向边.
(3)重复上述两步,直到剩余的网中不再存在没有前趋的顶点为止.
题解:
#include<iostream>
#include<cstdio>
using namespace std;
const int maxn=50000+10;
struct cc{
int from,to;
}es[maxn];
int ru[maxn];
int first[maxn],next[maxn],dis[maxn];
bool vis[maxn];
int tot=0;
void build(int ff,int tt)
{
es[++tot]=(cc){ff,tt};
next[tot]=first[ff];
first[ff]=tot;
}
int n;
void TopoSort()
{
for(int i=1;i<=n;i++)
{
if(!ru[i]&&!vis[i])
{
printf("%d ",i);
vis[i]=1;
for(int j=first[i];j;j=next[j])
{
int u=es[j].to;
if(!vis[u])
{
ru[u]--;
if(!ru[u])
{
TopoSort();
}
}
}
}
}
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
int x;
while(scanf("%d",&x))
{
if(x==0)
{
break;
}
build(i,x);
ru[x]++;
}
}
TopoSort();
return 0;
}