【题目】
LOJ
给定一棵有根树,每个节点有一个所需空间
m
i
m_i
mi,你可以将一段内存
S
S
S分成任意多个段
S
i
S_i
Si,然后将每个节点分别放入一个段中,满足每个段
S
i
S_i
Si中的节点不存在祖先关系,且所需空间最大值为
S
i
S_i
Si。
求存在合法方案的最小
S
S
S。
n
≤
2
×
1
0
5
n\leq 2\times 10^5
n≤2×105
【解题思路】
这个不存在祖先关系的限制可以相当于一个点对子树内部的限制,对于子树的根必然需要新开一段。
如果我们将子树的分段最大值排序,考虑合并两个子树的信息。
一个贪心的思想是将最大值对应合并,这个是正确的,因为如果不是对应合并,最大值的影响始终会贡献给下一个值,并不能消除其影响。
我本来以为用
set
\text{set}
set启发式合并一下就可以了,结果发现可重的删除有点问题,所以只能用
priority_queue
\text{priority\_queue}
priority_queue了。不过写
splay
\text{splay}
splay就是一个
log
\log
log了。
使用 priority_queue \text{priority\_queue} priority_queue后复杂度 O ( n log 2 n ) O(n\log ^2 n) O(nlog2n),使用 splay \text{splay} splay后复杂度 O ( n log n ) O(n\log n) O(nlogn)
【参考代码】
#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;
}