版权声明:这是蒟蒻的BLOG,神犇转载也要吱一声哦~ https://blog.csdn.net/Dream_Lolita/article/details/89261029
【题目】
LOJ
给定一棵有根树,每个节点有一个所需空间
,你可以将一段内存
分成任意多个段
,然后将每个节点分别放入一个段中,满足每个段
中的节点不存在祖先关系,且所需空间最大值为
。
求存在合法方案的最小
。
【解题思路】
这个不存在祖先关系的限制可以相当于一个点对子树内部的限制,对于子树的根必然需要新开一段。
如果我们将子树的分段最大值排序,考虑合并两个子树的信息。
一个贪心的思想是将最大值对应合并,这个是正确的,因为如果不是对应合并,最大值的影响始终会贡献给下一个值,并不能消除其影响。
我本来以为用
启发式合并一下就可以了,结果发现可重的删除有点问题,所以只能用
了。不过写
就是一个
了。
使用 后复杂度 ,使用 后复杂度
【参考代码】
#include<bits/stdc++.h>
#define pb push_back
using namespace std;
typedef long long ll;
const int N=2e5+10;
int n,a[N],fa[N];
vector<int>E[N];
priority_queue<int>q[N],tmp;
int read()
{
int ret=0;char c=getchar();
while(!isdigit(c)) c=getchar();
while(isdigit(c)) ret=ret*10+(c^48),c=getchar();
return ret;
}
void dfs(int x)
{
for(auto v:E[x]) dfs(v);
int las=0;
for(auto v:E[x])
{
if(!las) las=v;
else
{
if(q[las].size()<q[v].size()) swap(q[las],q[v]);
while(!q[v].empty())
{
tmp.push(max(q[las].top(),q[v].top()));
q[las].pop();q[v].pop();
}
while(!tmp.empty()) q[las].push(tmp.top()),tmp.pop();
}
}
if(las) q[las].push(a[x]),swap(q[las],q[x]);
else q[x].push(a[x]);
}
int main()
{
#ifdef Durant_Lee
freopen("LOJ3052.in","r",stdin);
freopen("LOJ3052.out","w",stdout);
#endif
n=read();
for(int i=1;i<=n;++i) a[i]=read();
for(int i=2;i<=n;++i) fa[i]=read(),E[fa[i]].pb(i);
dfs(1);
ll ans=0;while(!q[1].empty()) ans+=q[1].top(),q[1].pop();
printf("%lld\n",ans);
return 0;
}