题解 P4577 【[FJOI2018]领导集团问题】
楼上两篇题解写的有一点点复杂,有map还写了离散化……
差分固然是一种理解方式,但其实有一种更好的理解方法和更简洁的代码。
那么现在我就来讲一讲
题意简述
文字语言:求树上最大权值随祖孙关系不降的点集大小
数学语言:求
为了方便描述,我们定义这种集合为“树上LIS”。
题解
考虑采用数学归纳法
类似处理序列LIS问题,对于每一个点
-
-
以
u 为根节点的ans_u=|f_u| (|f_u| 表示集合f_u 的大小)(该性质可由上述性质发现)
对于任意一个叶子节点
再考虑不是叶子节点的
假设点
首先,显然
现在我们考虑将
我们直接在multiset上二分出第一个
按照这样的方式在树上dfs即可求出
复杂度证明
该算法的复杂度为
考虑同样采用数学归纳法
记
我们需要证明
对于任意一个叶子节点
再考虑不是叶子节点的
假设点
那么
因为子孙们包含的节点个数
所以
启发式合并的复杂度为
所以
证毕。
代码
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
multiset<int> f[N];
multiset<int>::iterator it;
int n, w[N], ans;
int h[N], to[N], nxt[N], t;
bool comp(int x, int y) { return w[x] < w[y]; }
void add(int u, int v) { to[++t] = v, nxt[t] = h[u], h[u] = t; }
void merge(int u, int v) {
if(f[u].size() < f[v].size()) swap(f[u], f[v]);
for(it = f[v].begin(); it != f[v].end(); ++it) f[u].insert(*it);
}
void dfs(int u) {
for(int i = h[u]; i; i = nxt[i]) dfs(to[i]), merge(u, to[i]);
f[u].insert(w[u]);
it = f[u].lower_bound(w[u]);
if(it != f[u].begin()) f[u].erase(--it);
}
int main() {
scanf("%d", &n);
for(int i = 1; i <= n; ++i) scanf("%d", &w[i]);
for(int i = 2; i <= n; ++i) {
int f;
scanf("%d", &f);
add(f, i);
}
dfs(1);
printf("%d", f[1].size());
}