P15584 [KTSC 2026] 网格树 / Grid Tree
EuphoricStar · · 题解
考虑子任务 3。按照样例解释的图转
考虑子任务 4。定义任意子树的宽度序列
合法宽度序列必须要满足
我们自底向上求出每棵子树的宽度序列。叶子的宽度序列为
我们先在
但是
答案即为最终宽度序列的长度
考虑优化这个过程。容易发现
若暴力找不属于
时间复杂度
:::info[代码]
#include <bits/stdc++.h>
#define fst first
#define scd second
using namespace std;
using ll = long long;
using pll = pair<ll, ll>;
int a[200100][2], f[200100];
ll b[200100][2];
inline void ins(set<pll> &S, ll x) {
auto it = S.lower_bound(pll(x, 1e18));
if (it != S.begin() && prev(it)->scd >= x) {
x = prev(it)->scd + 1;
}
ll l = x, r = x;
if (it != S.end() && it->fst == x + 1) {
r = it->scd;
it = S.erase(it);
}
if (it != S.begin() && (--it)->scd + 1 == x) {
l = it->fst;
S.erase(it);
}
S.emplace(l, r);
}
auto dfs(int u) {
if (!a[u][0]) {
f[u] = 1;
return set<pll>{{-1, -1}};
}
int v = a[u][0], w = a[u][1];
auto L = dfs(v), R = dfs(w);
f[u] = f[v] + f[w];
ll x = max(L.rbegin()->scd + b[u][0], R.rbegin()->scd + b[u][1]);
if (f[v] < f[w]) {
swap(L, R);
}
for (pll p : R) {
for (ll x = max(0LL, p.fst); x <= p.scd; ++x) {
ins(L, x);
}
}
ins(L, max(x, L.rbegin()->scd + 1));
return L;
}
ll compute_min_depth(int n, vector<int> p, vector<int> c, vector<int> d) {
for (int i = 0; i <= n - 2; ++i) {
a[p[i]][d[i]] = i + 1;
b[p[i]][d[i]] = c[i];
}
return dfs(0).rbegin()->scd + 1;
}
:::