拓扑排序
什么是拓扑排序呢?
给定 个点 条边的有向图。将 个点整理成为一个序列,使得对于任意一条边 总有 的出点在 的入点之前,这样的序列我们就称它为图的拓扑序。
拓扑序的性质
-
只有有向无环图(DAG)才存在拓扑序。
-
同一张图的拓扑序不一定唯一。
拓扑排序的实现方法
① 首先统计所有点的入度 in[i]。
② 枚举所有点,并将入度为 0 的点插入队列。
③ 循环取出队头元素 top,并且输出,然后将 top 指向的所有点 的入度 - 1(in[y]--)。
④ 当 in[y] == 0 时,将 插入队列。
⑤ 重复步骤 ③、④,直到队列为空停止。
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);
}
}
}
}拓扑排序的时间复杂度为 ,其中 和 分别代表点数和边数。
例题
B3644 【模板】拓扑排序 / 家谱树
思路
拓扑排序函数
这就是个板子……
主函数
循环 次,然后每次都不停输入 ,直到 为 0 才停止。每次 的入度加一,然后 向 连有向边。
#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 一定有拓扑序。
⑤ 维护计数器 来表示出队的点数,若 ,则说明是 ,否则有 个点在环上。
⑥ 维护计数器 表示位置 处的摄像头数量。
#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;
}