【贪心+堆启发式合并】LOJ3052 [十二省联考 2019] 春节十二响

【题目】
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 n2×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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值