拓扑排序的定义为,若存在边 u → v u\rightarrow v u→v,则 u u u 的拓扑序小于 v v v。拓扑排序是针对 DAG(有向无环图)而言的。
拓扑排序的流程如下:
- 记录每个点的度数,把度数为 0 0 0 的点加入队列并输出。
- 当队列非空时,取出队首元素,更新与其相连的点的度数。若出现度数为 0 0 0 的点,输出并将其加入队列。
注意 N N N 个点的图最多有 N × ( N − 1 ) N\times (N-1) N×(N−1) 条边。
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int maxn=105;
struct edge{int to,nxt;}e[maxn*maxn];
int head[maxn],cnt,deg[maxn],N;
queue<int> q;
void add(int x,int y){e[++cnt]=(edge){y,head[x]},head[x]=cnt;}
void topo()
{
for(int i=1;i<=N;i++)
if(!deg[i]) q.push(i),cout<<i<<' ';
while(!q.empty())
{
int x=q.front();q.pop();
for(int i=head[x];i;i=e[i].nxt)
{
deg[e[i].to]--;
if(!deg[e[i].to]) cout<<e[i].to<<' ',q.push(e[i].to);
}
}
}
signed main()
{
cin>>N;
for(int i=1,a;i<=N;i++)
while(cin>>a&&a) add(i,a),deg[a]++;
topo();
return 0;
}