拓扑排序代码模板

一些注意的点都在代码注释中了。

cpp 复制代码
//有向图无环图中才有拓扑排序,且都是前面的编号的点指向后面编号的点
#include<iostream>
#include<cstring>
using namespace std;
const int N = 1e5 + 9;
int e[N], ne[N], h[N], idx, n, m, d[N], q[N];

void add(int a, int b)
{
	e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}

bool topsort()
{
	int hh = 0, tt = -1;
	//将所有入度为0的点入队,编号从1~n
	for (int i = 1; i <= n; ++i) if (!d[i]) q[++tt] = i;

	while (hh <= tt)
	{
		int t = q[hh++];//出队
		for (int i = h[t]; i != -1; i = ne[i])
		{
			int j = e[i];
			d[j]--;//因为t指向j,又因为t删除了,所以j入度减一
			if (!d[j]) q[++tt] = j;
		}
	}
	return tt == (n - 1);//如果每个点都入队了表明为拓扑排序
}

int main()
{
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	memset(h, -1, sizeof h);
	cin >> n >> m;
	for (int i = 0; i < m; ++i)
	{
		int a, b; cin >> a >> b;
		add(a, b);
		d[b]++;//入度加一
	}
	//队列中的顺序刚好就是拓扑排序,排序不唯一
	if (topsort()) for (int i = 0; i < n; ++i) cout << q[i] << " ";
	else cout << -1;
	return 0;
}
相关推荐
whxnchy44 分钟前
UDP多端口负载均衡实战
c++
sheeta19982 小时前
LeetCode 每日一题笔记 日期:2026.05.08 题目:3629. 素数跳跃最小次数
笔记·算法·leetcode
叼烟扛炮2 小时前
C++ 知识点08 类与对象
开发语言·c++·算法·类和对象
米粒12 小时前
力扣算法刷题 Day 63 Bellman_ford 算法
数据库·算法·leetcode
楼田莉子2 小时前
仿Muduo的高并发服务器:Http协议模块
linux·服务器·c++·后端·学习
IT大白鼠9 小时前
AIGC性能的关键瓶颈:算力、数据、算法三者如何互相制约?
算法·aigc
tjl521314_219 小时前
04C++ 名称空间(Namespace)
开发语言·c++
ximu_polaris9 小时前
设计模式(C++)-行为型模式-备忘录模式
c++·设计模式·备忘录模式
白雪茫茫9 小时前
监督学习、半监督学习、无监督学习算法详解
python·学习·算法·ai
FengyunSky9 小时前
浅析 空间频率响应 SFR 计算
算法