P17878 题解
Gapple
·
·
题解
40 pts
考虑二分答案,这样问题转化成判定中位数能否 \ge m。假设我们已经断好了边,我们把和 \ge m 的连通块设成 +1,< m 的设成 -1。这样 \ge m 其实就是连通块之和 > 0。
我会树形 DP!设 f(i, j, 0/1) 表示以 i 为根的子树中,子树内的连通块(不包括 i 所在的连通块,不然难以转移)之和为 j,当前断了奇数 / 偶数条边时,i 所在的连通块的点权和的最大值。
转移形如树上背包。假设我们要把 u 的儿子 v 合并上来。设 [P] 在命题 P 为真时取 +1,反之取 -1,则转移方程为:
- 断掉边 (u, v):f(u, x_1, y_1) \to f'(u, x_1 + x_2 + [f(v, x_2, y_2) \ge m], (y_1 + y_2 + 1) \bmod 2)。
- 不断边 (u, v):f(u, x_1, y_1) + f(v, x_2, y_2) \to f'(u, x_1 + x_2, (y_1 + y_2) \bmod 2)。
这样,判定中位数能否 \ge m 就变成了判断是否存在 i \in [0, n] 使得 [f(1, i, 0) \ge m] + i > 0 是否成立,O(n) 扫一遍即可。
### 100 pts
感谢 @[sea_water](luogu://user/806720) 提供这个 idea。
注意到如果某个子树中 $f(i, 3, 0/1)$ 是合法状态,那么把 $i$ 和它的父亲的边断掉后,连通块的和一定还 $> 0$。于是第 2 维只需开 $[-3, 3]$ 即可。
进一步的,实际上我们也不需要维护当前断了奇数条边还是偶数条边。因为若连通块之和 $> 0$,那么即使多断一条边,连通块之和一定还能 $\ge 0$。
$O(n \log V)$。
:::info[代码]
```cpp
#include <algorithm>
#include <array>
#include <iostream>
#include <utility>
#include <vector>
using namespace std;
using i64 = long long;
constexpr i64 INF = 0x3f3f3f3f3f3f3f3f;
constexpr array<i64, 4> INIT { -INF, -INF, -INF, -INF };
inline void setmax(i64& x, i64 y) { x = max(x, y); }
struct Solution {
int n;
vector<i64> w;
vector<vector<int>> tree;
vector<array<i64, 4>> f;
void solve(i64 med, int u = 1, int fa = -1)
{
f[u][1] = w[u];
for (int v : tree[u]) {
if (v == fa)
continue;
solve(med, v, u);
array g = INIT;
for (int j = -1; j <= 2; ++j) {
if (f[u][j + 1] <= -INF)
continue;
for (int l = max(-1, -1 - j); l <= 2 && l <= 2 - j; ++l) {
if (f[v][l + 1] <= -INF)
continue;
int idx = j + (f[v][l + 1] >= med ? 1 : -1) + l;
setmax(g[j + l + 1], f[u][j + 1] + f[v][l + 1]);
if (-1 <= idx && idx <= 2)
setmax(g[idx + 1], f[u][j + 1]);
}
}
f[u] = std::move(g);
}
}
bool check(i64 med)
{
f.assign(n + 1, INIT);
solve(med);
for (int j = 0; j <= 2; ++j) {
if (f[1][j + 1] > -INF && j + (f[1][j + 1] >= med ? 1 : -1) > 0)
return true;
}
return false;
}
void main()
{
cin >> n;
w.resize(n + 1);
for (int i = 1; i <= n; ++i)
cin >> w[i];
tree.resize(n + 1);
for (int i = 1; i < n; ++i) {
int u, v;
cin >> u >> v;
tree[u].push_back(v);
tree[v].push_back(u);
}
i64 l = -INF, r = INF;
while (l < r) {
i64 mid = (l + r + 1) >> 1;
if (check(mid))
l = mid;
else
r = mid - 1;
}
cout << l << '\n';
}
};
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int c, t;
cin >> c >> t;
while (t-- > 0)
Solution().main();
return 0;
}
```
:::