跳到正文

个人记录

拓扑排序

Moonlight_dreams约 6 分钟
原文
文章信息与版本

文章信息

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

版本

  1. v1当前

拓扑排序

什么是拓扑排序呢?

给定 nn 个点 mm 条边的有向图。将 nn 个点整理成为一个序列,使得对于任意一条边 ii 总有 ii 的出点在 ii 的入点之前,这样的序列我们就称它为图的拓扑序。

拓扑序的性质

  • 只有有向无环图(DAG)才存在拓扑序。

  • 同一张图的拓扑序不一定唯一。

拓扑排序的实现方法

① 首先统计所有点的入度 in[i]。

② 枚举所有点,并将入度为 0 的点插入队列。

③ 循环取出队头元素 top,并且输出,然后将 top 指向的所有点 yy 的入度 - 1(in[y]--)。

④ 当 in[y] == 0 时,将 yy 插入队列。

⑤ 重复步骤 ③、④,直到队列为空停止。

C++
void topo()
{
	for (int i = 1; i <= n; i++)
	{
		if (in[i] == 0)
		{
			qu.push(i);
		}
	}
	while (qu.empty() == 0)
	{
		int top = qu.front();
		qu.pop();
		cout << top << " ";
		for (int i = 0; i < g[top].size(); i++)
		{
			int nxt = g[top][i];
			in[nxt]--;
			if (in[nxt] == 0)
			{
				qu.push(nxt);
			}
		}
	}
}
拓扑排序的时间复杂度为 O(n+m)O(n+m),其中 nn 和 mm 分别代表点数和边数。

例题

B3644 【模板】拓扑排序 / 家谱树

思路

拓扑排序函数

这就是个板子……

主函数

循环 nn 次,然后每次都不停输入 sonson,直到 sonson 为 0 才停止。每次 sonson 的入度加一,然后 ii 向 sonson 连有向边。

AC代码如下AC 代码如下

C++
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 105;
int n;
vector <int> g[N];
queue <int> qu;
int in[N];
void topo()
{
	for (int i = 1; i <= n; i++)
	{
		if (in[i] == 0)
		{
			qu.push(i);
		}
	}
	while (qu.empty() == 0)
	{
		int top = qu.front();
		qu.pop();
		cout << top << " ";
		for (int i = 0; i < g[top].size(); i++)
		{
			int nxt = g[top][i];
			in[nxt]--;
			if (in[nxt] == 0)
			{
				qu.push(nxt);
			}
		}
	}
}
signed main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	cin >> n;
	for (int i = 1; i <= n; i++)
	{
		int son;
		while (cin >> son)
		{
			if (son == 0)
			{
				break;
			}
			in[son]++;
			g[i].push_back(son);
		}
	}
	topo();
	return 0;
}

P2712 摄像头

思路

① 若位置 x 可以照到位置 y,则 x 向 y 连有向边。

② 合法的破坏顺序就是一个拓扑序。

③ 若有向图构成环,则环上的点是不能得到拓扑序,因为入度不能为 0。

④ 若一个点,x 能够进队或出队,那么 x 一定有拓扑序。

⑤ 维护计数器 cntcnt 来表示出队的点数,若 cnt==ncnt == n,则说明是 YESYES,否则有 n−cntn - cnt 个点在环上。

⑥ 维护计数器 id[x]id[x] 表示位置 xx 处的摄像头数量。

AC代码如下AC 代码如下

C++
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 505;
int n;
vector <int> g[N];
queue <int> qu;
int in[N] , id[N];
void topo()
{
	for (int i = 0; i <= 500; i++)
	{
		if (id[i] > 0 && in[i] == 0)
		{
			qu.push(i);
		}
	}
	int cnt = 0;
	while (qu.empty() == 0)
	{
		int top = qu.front();
		qu.pop();
		// cout << top << " ";
		cnt += id[top];
		for (int i = 0; i < g[top].size(); i++)
		{
			int nxt = g[top][i];
			in[nxt]--;
			if (in[nxt] == 0)
			{
				qu.push(nxt);
			}
		}
	}
	// cout << endl;
	// cout << cnt << endl;
	if (cnt == n)
	{
		cout << "YES";
	}
	else
	{
		cout << n - cnt;
	}
}
signed main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	cin >> n;
	for (int i = 1; i <= n; i++)
	{
		int x , m;
		cin >> x >> m;
		id[x]++;
		while (m--)
		{
			int y;
			cin >> y;
			g[x].push_back(y);
			in[y]++;
		}
	}
	topo();
	return 0;
}
原文