P5290 [十二省联考2019]春节十二响

从特殊到一般

我们先看链的情况。

我们把点$1$左右的两条子链分别扔入堆里

每次取出两个堆的最大值,把答案累加上更大的那个(另一堆为空则直接加上去)。

那么......如果$1$连着多条链咋办?

我们又发现,你可以每次把每2条链所对的堆两两合并,并不影响答案。

那么......如果$1$连着多棵树咋办?

其实是链是树已经没多大区别了,因为它们之间互不影响。

于是做法就出来了

dfs把子树合并,一层层合并上去就好辣

注意为了保证复杂度$O(nlog^2n)$,我们要做启发式合并,就是每次把小的堆合并到大的堆上去

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
inline int Max(int a,int b){return a>b?a:b;}
inline void Swap(int &a,int &b){a^=b^=a^=b;}
void read(int &x){
char c=getchar();x=;
while(c<''||c>'') c=getchar();
while(''<=c&&c<='') x=x*+(c^),c=getchar();
}
#define N 200005
int n,val[N],tp,tmp[N],id[N]; long long ans;
int cnt,hd[N],nxt[N],ed[N],poi[N];
priority_queue <int> h[N];
inline void adde(int x,int y){
nxt[ed[x]]=++cnt, hd[x]=hd[x]?hd[x]:cnt,
ed[x]=cnt, poi[cnt]=y;
}
void merge(int &x,int &y){
if(h[x].size()<h[y].size()) Swap(x,y);//启发式合并
while(!h[y].empty()){
tmp[++tp]=Max(h[x].top(),h[y].top());
h[x].pop(); h[y].pop();
}
while(tp) h[x].push(tmp[tp--]);
}
void dfs(int x){
id[x]=x;
for(int i=hd[x];i;i=nxt[i])dfs(poi[i]),merge(id[x],id[poi[i]]);
h[id[x]].push(val[x]);
}
int main(){
read(n);
for(int i=;i<=n;++i) read(val[i]);
for(int i=,q;i<=n;++i) read(q),adde(q,i);
dfs();
while(!h[id[]].empty()) ans+=h[id[]].top(),h[id[]].pop();
printf("%lld",ans);
return ;
}

最新文章

  1. Windows 下的 Redis 的启动
  2. Chrome console命令整理
  3. iOS 判断字符串是否为空
  4. SPFA算法
  5. jQuery插件开发教程
  6. 凸多边形的三角剖分(dp好题)
  7. linux下udp编程
  8. 证明Dijkstra中加入S的点已经最优
  9. windows下 tomcat7 配置成服务
  10. Laravel框架——增删改查
  11. html基本框架
  12. 如何防范CC攻击
  13. 可编辑DIV (contenteditable=&quot;true&quot;) 在鼠标光标处插入图片或者文字
  14. Timestamp解析0000-00-00 00:00:00报格式错误
  15. Python with
  16. Dynamics CRM build numbers
  17. MyBatis-Spring中间件逻辑分析(怎么把Mapper接口注册到Spring中)
  18. (六)jdk8学习心得之Stream流
  19. 【Linux】-- 在linux上安装mysql及基本操作
  20. 【清北学堂2018-刷题冲刺】Contest 6

热门文章

  1. inner join, left join, right join 和 full join
  2. xxx.app已损坏,打不开.你应该将它移到废纸篓-已解决
  3. js抽红包分配
  4. 极限树(extraTree)总结
  5. fullpage插件在移动端弹出键盘页面特殊处理
  6. _proto_ 和prototype自己的理解
  7. 使用Eclipse出现make: *** No rule to make target `all&#39;. Stop.解决办法
  8. MFC 运行报错:Debug Assertion Failed! dbgheap.c
  9. codeforces 185A Plant(推公式)
  10. 关于hibernate总是报错 配置factory的id找不到,mapping配置文件Could not parse mapping document from input stream