【洛谷P1090,SSL1040】合并果子【堆】

98 篇文章 0 订阅
29 篇文章 0 订阅
这篇博客主要分析了如何合并果子的问题,通过两种方法实现:使用STL的堆和手动构建堆。作者提供了详细的代码示例,解释了在解决此类问题时如何利用堆数据结构找到并添加最小元素。
摘要由CSDN通过智能技术生成

在这里插入图片描述

分析:

找最小的加入堆

s t l   C o d e : stl~Code: stl Code

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#define reg register
using namespace std;
typedef long long ll;
int n,ans;
priority_queue<int,vector<int>,greater<int> > q;
int main(){
	scanf("%d",&n);
	for(int i=1,x;i<=n;i++)
	{
		scanf("%d",&x);
		q.push(x);
	}
	while(q.size()>=2)
	{
		int x=q.top(); q.pop();
		int y=q.top(); q.pop();
		ans+=x+y;
		q.push(x+y);
	}
	printf("%d",ans);
	return 0;
}

手打堆 C o d e : Code: Code

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#define reg register
using namespace std;
typedef long long ll;
const int N=1e4+5;
int n,ans,a[N],tot;
namespace Heap{
	void down(int x)
	{
		while((x<<1)<=tot&&a[x]>a[x<<1]||(x<<1|1)<=tot&&a[x]>a[x<<1|1])
		{
			int son=x<<1;
			if(son+1<=tot&&a[son+1]<a[son]) son++;
			swap(a[x],a[son]);
			x=son;
		}
	}
	void up(int x)
	{
		while(x&&a[x]<a[x>>1])
		{
			swap(a[x],a[x>>1]);
			x>>=1;
		}
	}
	void push(int x)
	{
		a[++tot]=x;
		up(tot);
	}
	void pop(int x)
	{
		if(a[x]<a[tot]) a[x]=a[tot--],down(x);
		else a[x]=a[tot--],up(x);
	}
}
int main(){
	scanf("%d",&n);
	for(int i=1,x;i<=n;i++)
	{
		scanf("%d",&x);
		Heap::push(x);
	}	
	while(tot>=2)
	{
		int x=a[1]; Heap::pop(1);
		int y=a[1]; Heap::pop(1);
		ans+=x+y;
		Heap::push(x+y);
	}
	printf("%d",ans);
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值