堆排 luogu1090合并果子

此题为堆排的简单运用

#include<cstdio>
#include<iostream>
using namespace std;
int ans,s,hp[10005],n,siz,cnt;
void pus(int x)//输(插)入 
{
cnt++;
hp[cnt]=x;
int now=cnt;
int fa=cnt/2;
while(now>1)
{
if(hp[now]>=hp[fa])
return;
else
{
swap(hp[now],hp[fa]);
now=fa,fa/=2;
}
}
}
int del()//删除堆顶 维护堆 
{
int res=hp[1];
swap(hp[1],hp[cnt]);
cnt--;
int now=1;
while(2*now<=cnt)//有儿子 
{
int lison=2*now;
if(lison<cnt && hp[lison+1]<hp[lison])//有右儿子
lison++;
if(hp[now]>hp[lison])
swap(hp[now],hp[lison]),now=lison;
else break;
}
return res;

int main()
{
cin>>n;
int a;
for(int i=1;i<=n;i++)
{
cin>>a;
pus(a);//建堆 
}
for(int i=1;i<n;i++)
{
int a1=del();//提取两个最小值
int a2=del();
int s=a1+a2;
ans+=s;
pus(s); 
}
cout<<ans<<endl;
return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值