题面

给定一棵n个节点的有根树,编号依次为1到n,其中1号点为根节点。每个点有一个权值v_i。

你需要将这棵树转化成一个大根堆。确切地说,你需要选择尽可能多的节点,满足大根堆的性质:对于任意两个点i,j,如果i在树上是j的祖先,那么v_i>v_j。

请计算可选的最多的点数,注意这些点不必形成这棵树的一个连通子树。

分析

由于点不需要相邻,此题其实是树上的LIS,从叶子节点向根节点形成LIS

考虑LIS的\(O(nlogn)\)算法中用到的数组,用multiset对每个节点维护这样一个数组,存储子树内的值

向上的同时合并两个multiset,用启发式合并

时间复杂度应该是\(O(nlog^2n)\)

代码

#include<iostream>
#include<cstdio>
#include<cstring>
#include<set>
#define maxn 200005
using namespace std;
int n;
struct edge{
int from;
int to;
int next;
}E[maxn<<1];
int head[maxn];
int sz;
void add_edge(int u,int v){
sz++;
E[sz].from=u;
E[sz].to=v;
E[sz].next=head[u];
head[u]=sz;
} int a[maxn];
multiset<int>s[maxn];
void merge(int x,int y){//启发式合并
if(s[x].size()<s[y].size()) swap(s[x],s[y]);
for(multiset<int>::iterator it=s[y].begin();it!=s[y].end();it++){
s[x].insert(*it);
}
}
void dfs(int x,int fa){
for(int i=head[x];i;i=E[i].next){
int y=E[i].to;
if(y!=fa){
dfs(y,x);
merge(x,y);
}
}
multiset<int>::iterator it=s[x].lower_bound(a[x]);
if(it==s[x].end()) s[x].insert(a[x]);
else{
s[x].erase(it);
s[x].insert(a[x]);
}
}
int main(){
int fa;
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%d %d",&a[i],&fa);
if(fa!=0){
add_edge(i,fa);
add_edge(fa,i);
}
}
dfs(1,0);
printf("%d\n",s[1].size());
}

最新文章

  1. 深入理解java异常处理机制
  2. Map集合遍历的2种方法
  3. HDU-Minimum Inversion Number(最小逆序数)
  4. linux中ssh可以登录sftp不能登录解决办法
  5. HDU1518 Square(DFS)
  6. Codeforces 161 B. Discounts (贪心)
  7. C# 静态类
  8. ASP.NET 应用程序(Application)生命周期概述
  9. H264 Decoder
  10. Intellij IDEA 没办法创建java文件
  11. js常会问的问题:找出字符串中出现次数最多的字符。
  12. JavaScript面向对象--继承 (超简单易懂,小白专属)
  13. Linux用户、用户组、文件权限学习笔记
  14. C#中的double类型数据向SQL sqerver 存储与读取问题
  15. MAC上使用Enterprise Architecture,附带安装步骤及破解链接
  16. JS DOM操作(三) Window.docunment对象——操作属性
  17. python_ssh连接
  18. `Vue`中为什么访问不了以`$`和`_`开头的属性?
  19. 【最大流/二分图匹配】【网络流24题】【P3254】 圆桌问题
  20. eclipse 无法解析导入 javax.servlet 的解决方法

热门文章

  1. Django【第21篇】:Ajax之FormData
  2. 【leetcode】1111. Maximum Nesting Depth of Two Valid Parentheses Strings
  3. 2019年开发App记录
  4. spring mvc 数据校验(bean实体注解实现)
  5. class和style绑定
  6. HDU 6230 Palindrome ( Manacher &amp;&amp; 树状数组)
  7. 博弈论 x
  8. 洛谷p3955 图书管理员(NOIP2017 t2)
  9. 【FJ省队训练&amp;&amp;NOIP夏令营】酱油&amp;&amp;滚粗记
  10. [ethereum源码分析](4) ethereum运行开启console