-图论-拓扑排序- [LOJ 2114]「HNOI2015」菜肴制作

题目描述

Link

Solution

题目要求中说尽可能让编号小的优先,还要满足做菜顺序,于是我们可以将队列换成优先队列,然后再反向建图跑拓扑就行了,最后倒序输出。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#define MAXN 100101
struct Edge {
int v, nx;
}e[MAXN << 1];
int head[MAXN], ecnt, n, T, m, x, y, ent[MAXN], st[MAXN], top, fl;
void add(int f, int t) {
e[++ecnt] = (Edge) {t, head[f]};
head[f] = ecnt;
}
int main() {
scanf("%d", &T);
while (T--) {
memset(head, 0, sizeof(head));
memset(ent, 0, sizeof(ecnt));
memset(ent, 0, sizeof(ent));
ecnt = 0;
top = 0;
scanf("%d%d", &n, &m);
for (int i = 1; i <= m; i++) {
scanf("%d%d", &x, &y);
add(y, x);
ent[x]++;
}
std::priority_queue <int> q;
for (int i = 1; i <= n; i++) {
if (!ent[i]) q.push(i);
}
while (!q.empty()) {
int u = q.top();
st[++top] = u;
q.pop();
for (int i = head[u]; i; i = e[i].nx) {
int to = e[i].v;
ent[to]--;
if (!ent[to]) q.push(to);
}
}
fl = 0;
for (int i = 1; i <= n; i++) {
if (ent[i] >= 1) fl = 1;
}
if (fl) {
puts("Impossible!");
continue;
}
for (int i = top; i >= 1; i--) {
printf("%d ", st[i]);
}
puts("");
}
}
文章作者: RiverFun
文章链接: https://stevebraveman.github.io/blog/2019/09/16/101/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 RiverFun

评论