跳到正文

个人记录

拓扑排序模板(无废话)

阿哲朗读约 1 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 1 分钟

版本

  1. v1当前
C++
#include<bits/stdc++.h>
using namespace std;
int cnt,head[10001],rd[10001],n,m;
struct Edge
{
	int to,next;
}a[20001];
void AddEdge(int start,int end)
{
	cnt++;
	a[cnt].to=end;
	a[cnt].next=head[start];
	head[start]=cnt;
	return;
}
void Topsort()
{
	queue<int>q;
	for(int i=1;i<=n;i++)
	{
		if(rd[i]==0) q.push(i);
	}
	while(!q.empty())
	{
		int node=q.front();
		cout<<node<<" ";
		q.pop();
		rd[node]=-1;
		for(int i=head[node];i;i=a[i].next)
		{
			rd[a[i].to]--;
			if(rd[a[i].to]==0) q.push(a[i].to);
		}
	}
	return;
}
int main()
{
	int x,y;
	cin>>n>>m;
	for(int i=1;i<=m;i++)
	{
		cin>>x>>y;
		AddEdge(x,y);
		rd[y]++;
	}
	Topsort();
	return 0;
 }
原文