Luogu P1552 [APIO2012]派遣

题目描述

https://www.luogu.com.cn/problem/P1552

Solution

我们考虑直接 $dfs$,枚举以每个点作为管理者的情况

那么一个点作为管理者所能得到的最大值一定是子树内保留薪资最小的若干点,使得他们的和不超过 $m$

这个东西显然可以维护大根堆,然后我们需要的操作就是合并和删除最大值,这个可以用左偏树实现

当然也可以 $set$ 启发式合并,但这个是两个 $log$ 的

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
#include <iostream>
#include <cstdio>
#define maxn 100010
#define ll long long
using namespace std;

int n, m, a[maxn], b[maxn];

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

#define lc T[x].ch[0]
#define rc T[x].ch[1]
struct LLT {
int v, d, ch[2], sz;
ll sum;
} T[maxn]; int rt[maxn];
inline void maintain(int x) {
T[x].sz = T[lc].sz + T[rc].sz + 1;
T[x].sum = T[lc].sum + T[rc].sum + T[x].v;
T[x].d = T[rc].d + 1;
}

int merge(int x, int y) {
if (!x || !y) return x + y;
if (T[x].v < T[y].v) swap(x, y);
rc = merge(rc, y);
if (T[lc].d < T[rc].d) swap(lc, rc);
maintain(x); return x;
}

inline int erase(int x) { return merge(lc, rc); }

ll ans;
void dfs(int u, int fa) {
for (int i = head[u]; ~i; i = e[i].next) {
int v = e[i].to; if (v == fa) continue;
dfs(v, u); rt[u] = merge(rt[u], rt[v]);
}
while (T[rt[u]].sum > m) rt[u] = erase(rt[u]);
ans = max(ans, 1ll * T[rt[u]].sz * b[u]);
}

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

cin >> n >> m; T[0].d = -1;
for (int i = 1; i <= n; ++i) {
int x; cin >> x >> a[i] >> b[i];
if (x) add_edge(x, i);
else Rt = i;
}
for (int i = 1; i <= n; ++i) T[i] = { a[i], 1, 0, 0, 1, a[i] }, rt[i] = i;
dfs(Rt, 0); cout << ans << "\n";
return 0;
}