拓扑排序
拓扑排序:
head[u]: 以u为起点的边,最前面的边的编号
拓朴排序模板:邻接表(结构体+队列实现)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
const int maxn = 1e5+5;
int head[maxn],in[maxn],topo[maxn],n,m,num;
struct Edge{
int u;
int v;
int next;
}edge[maxn];
void addEdge(int u,int v){
edge[num].u = u;
edge[num].v = v;
edge[num].next = head[u];
head[u] = num++;
}
void init(){
memset(head,-1,sizeof(head));
memset(in,0,sizeof(in));
}
int topoSort()
{
queue<int>q;
for(int i=1;i<=n;i++)
{
if(in[i]==0){
q.push(i);
}
}
int t = 0;
while(!q.empty())
{
int u=q.front();
q.pop();
topo[t++]=u;
for(int i=head[u]; i!=-1; i=edge[i].next){
int v=edge[i].v;
in[v]--;
if(in[v]==0){
q.push(v);
}
}
}
}
int main()
{
init();
cin>>n>>m;
for(int i=0;i<m;i++){
int u,v;
cin>>u>>v;
in[v]++;
addEdge(u,v);
}
topoSort();
for(int i=0;i<n;i++){
cout<<topo[i]<<" ";
}
return 0;
}
/*
7 7
1 7
2 3
2 4
3 4
3 5
6 5
7 6
topo:1 2 7 3 6 4 5
*/