Description
给定一棵n个节点的有根树,编号依次为1到n,其中1号点为根节点。每个点有一个权值v_i。
你需要将这棵树转化成一个大根堆。确切地说,你需要选择尽可能多的节点,满足大根堆的性质:对于任意两个点i,j,如果i在树上是j的祖先,那么v_i>v_j。
请计算可选的最多的点数,注意这些点不必形成这棵树的一个连通子树。
第一行包含一个正整数n(1<=n<=200000),表示节点的个数。
接下来n行,每行两个整数v_i,p_i(0<=v_i<=10^9,1<=p_i<i,p_1=0),表示每个节点的权值与父亲。
Solution
一个n^2的dp是f[i,j]表示节点i内最大值不大于j的答案,转移就是分别和儿子合并然后添上i,然后我就不会了。。
考虑一条链的情况,这其实是一个lis问题。注意到多棵子树互不影响,我们每个节点用multiset记录长度为i时最大值的最小值,合并的时候启发式合并,然后添上当前节点就可以了
因为增加一个数后lis是不降的,我们插入一个数字只会造成长度+1、长度不变但最大值变小、无影响这三种情况,于是乎每次只需要删一个数字就可以了
一开始没有删掉没用的set爆了。。
Code
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <set>
#define rep(i,st,ed) for (int i=st;i<=ed;++i)
typedef std:: multiset <int> set;
const int N=500005;
struct edge {int y,next;} e[N];
int ls[N],w[N],edCnt;
set s[N];
int read() {
int x=0,v=1; char ch=getchar();
for (;ch<'0'||ch>'9';v=(ch=='-')?(-1):(v),ch=getchar());
for (;ch<='9'&&ch>='0';x=x*10+ch-'0',ch=getchar());
return x*v;
}
void add_edge(int x,int y) {
e[++edCnt]=(edge) {y,ls[x]}; ls[x]=edCnt;
}
void solve(int x) {
for (int i=ls[x];i;i=e[i].next) {
solve(e[i].y);
if (s[x].size()<s[e[i].y].size()) std:: swap(s[x],s[e[i].y]);
for (set:: iterator it=s[e[i].y].begin();it!=s[e[i].y].end();it++) {
s[x].insert(*it);
}
s[e[i].y].clear();
}
set:: iterator it=s[x].lower_bound(w[x]);
if (it!=s[x].end()) s[x].erase(it);
s[x].insert(w[x]);
}
int main(void) {
int n=read();
rep(i,1,n) {
w[i]=read(); int f=read();
if (f) add_edge(f,i);
}
solve(1);
printf("%d\n", (int)s[1].size());
return 0;
}