CF 1463E Plan of Lectures

题目描述

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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <iostream>
#include <cstdio>
#include <queue>
#include <vector>
#define maxn 300010
#define INF 200000000
using namespace std;

int n, m;

struct Edge {
int to, next;
} e[maxn]; int c1, head[maxn], in[maxn];
inline void add_edge(int u, int v) {
e[c1].to = v; e[c1].next = head[u]; head[u] = c1++;
}

vector<int> G[maxn], V[maxn], ans[maxn];

int cnt, id[maxn], rk[maxn];
void dfs(int u, int o) {
id[u] = o; ans[o].push_back(u);
for (auto v : G[u]) {
if (id[v]) cout << "0\n", exit(0);
rk[v] = rk[u] + 1; dfs(v, o);
}
}

vector<int> Ans;
void topsort() {
queue<int> Q;
for (int i = 1; i <= cnt; ++i)
if (!in[i]) Q.push(i);
while (!Q.empty()) {
int u = Q.front(); Q.pop(); Ans.push_back(u);
for (int i = head[u]; ~i; i = e[i].next) {
int v = e[i].to;
if (--in[v] == 0) Q.push(v);
}
}
}

int main() { fill(head, head + maxn, -1);
ios::sync_with_stdio(false);
cin.tie(nullptr); cout.tie(nullptr);

cin >> n >> m;
for (int i = 1; i <= n; ++i) {
int x; cin >> x;
if (x) V[x].push_back(i);
}
for (int i = 1; i <= m; ++i) {
int x, y; cin >> x >> y;
G[x].push_back(y); ++in[y];
}
for (int i = 1; i <= n; ++i)
if (!in[i]) dfs(i, ++cnt);
for (int i = 1; i <= n; ++i)
if (!id[i]) return cout << "0\n", 0;
fill(in, in + maxn, 0);
for (int u = 1; u <= n; ++u)
for (auto v : V[u]) {
if (id[u] == id[v] && rk[v] < rk[u]) return cout << "0\n", 0;
else if (id[u] != id[v]) add_edge(id[u], id[v]), ++in[id[v]];
}
topsort();
for (int i = 1; i <= cnt; ++i)
if (in[i]) return cout << "0\n", 0;
for (auto u : Ans)
for (auto v : ans[u]) cout << v << " ";
return 0;
}