拓扑排序
定义
拓扑排序
Kahn 算法
过程
初始状态下,集合
不断重复以上过程,直到集合
时间复杂度
假设这个图
因而总的时间复杂度就有
例题
B3644 【模板】拓扑排序 / 家谱树
:::info[
#include <bits/stdc++.h>
using namespace std;
int n,a[10004],into[10004],t,vis[10004];
vector<int>edge[10004];
queue<int>q;
int main()
{
cin>>n;
for(int i=1;i<=n;i++)
{
while(cin>>t)
{
if(t==0)break;
edge[i].push_back(t);
into[t]++;
}
}
for(int i=1;i<=n;i++)
if(into[i]==0&&!vis[i])q.push(i),vis[i]=1;
while(!q.empty())
{
int u=q.front();
q.pop();
cout<<u<<" ";
for(int i=0;i<edge[u].size();i++)
into[edge[u][i]]--;
for(int i=1;i<=n;i++)
if(into[i]==0&&!vis[i])q.push(i),vis[i]=1;
}
return 0;
}
:::