Description
给定一棵n个节点的有根树,编号依次为1到n,其中1号点为根节点。每个点有一个权值v_i。
你需要将这棵树转化成一个大根堆。确切地说,你需要选择尽可能多的节点,满足大根堆的性质:对于任意两个点i,j,如果i在树上是j的祖先,那么v_i>v_j。
请计算可选的最多的点数,注意这些点不必形成这棵树的一个连通子树。
Input
第一行包含一个正整数n(1<=n<=200000),表示节点的个数。
接下来n行,每行两个整数v_i,p_i(0<=v_i<=10^9,1<=p_i<i,p_1=0),表示每个节点的权值与父亲。
Output
输出一行一个正整数,即最多的点数。
Sample Input
6
3 0
1 1
2 1
3 1
4 1
5 1
Sample Output
5
分析:
显然是一道树上的lis。
对于一般的二分的lis来说,每次可以二分一个
≥
x
≥x
≥x的数,然后用
x
x
x去替换它。
对于一个节点来说,各个子树的lis相互独立。也就是可以先把子树合并成一个,然后再把当前节点权值看做
x
x
x对当前序列操作。
可以使用multiset进行维护,使用启发式合并,合并后要清空其中一个数组,保证空间可以承受。
代码:
/**************************************************************
Problem: 4919
User: liangzihao
Language: C++
Result: Accepted
Time:872 ms
Memory:20780 kb
****************************************************************/
#include <iostream>
#include <cstdio>
#include <cmath>
#include <set>
#include <algorithm>
const int maxn=2e5+7;
using namespace std;
int n,x,cnt;
int a[maxn],ls[maxn];
struct edge{
int y,next;
}g[maxn];
multiset <int> s[maxn];
void add(int x,int y)
{
g[++cnt]=(edge){y,ls[x]};
ls[x]=cnt;
}
void merge(int x,int y)
{
if (s[x].size()>s[y].size()) swap(s[x],s[y]);
multiset <int>::iterator it=s[x].begin();
while (it!=s[x].end())
{
s[y].insert(*it);
it++;
}
s[x].clear();
}
void dfs(int x)
{
for (int i=ls[x];i>0;i=g[i].next)
{
int y=g[i].y;
dfs(y);
merge(y,x);
}
multiset <int>::iterator it=s[x].lower_bound(a[x]);
if (it!=s[x].end()) s[x].erase(it);
s[x].insert(a[x]);
}
int main()
{
scanf("%d",&n);
for (int i=1;i<=n;i++)
{
scanf("%d%d",&a[i],&x);
add(x,i);
}
dfs(1);
printf("%d\n",s[1].size());
}