【笔记/模板】拓扑排序

www.luogu.com.cn

拓扑排序

定义与实现思路

拓扑排序(Topological Sorting)是一个有向无环图(DAG, Directed Acyclic Graph)的所有顶点的线性序列。且该序列必须满足下面两个条件:

  1. 每个顶点出现且只出现一次。

  2. 若存在一条从顶点 A 到顶点 B 的路径,那么在序列中顶点 A 出现在顶点 B 的前面。

根据定义可知,我们可以使用队列+BFS的方式求出一个图的拓扑序列,方法如下:

  1. 存图的时候记录下每个点的前驱数(即入度)。

  2. 从图中选择一个 没有前驱(即入度为 \(0\))的顶点并输出,将其加入队列当中。

  3. 重复步骤 \(2\) 直到队列中的元素个数为 \(0\) 时,停止程序。

\(\bold tips\):通常,一个有向无环图可以有一个或多个拓扑排序序列。

代码实现

// Problem: B3644 【模板】拓扑排序 / 家谱树
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/B3644
// Memory Limit: 128 MB
// Time Limit: 1000 ms
//
// Powered by CP Editor (https://cpeditor.org)

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;

const int N = 1e3 + 9;
const int INF = 0x3f3f3f3f;
vector<int> g[N];
int n, x, in[N];
queue<int> q;

int main()
{
	// ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	cin >> n;
	for (int i = 1; i <= n; i++)
		while (cin >> x && x != 0)
		{
			g[i].push_back(x);
			in[x]++;
		}
	for (int i = 1; i <= n; i++)
		if (in[i] == 0)
		{
			cout << i << ' ';
			q.push(i);
		}
	while (!q.empty())
	{
		int x = q.front(); q.pop();
		for (auto i : g[x])
		{
			in[i]--;
			if (in[i] == 0) {
				cout << i << ' ';
				q.push(i);
			}
		}
	}
	return 0;
}
posted @   ThySecret  阅读(17)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示