【贪心】CODE[VS] 1063 NOIP2004普及组-合并果子 (刷题记录(模拟+优先队列))

本文介绍了一种基于贪心策略的算法实现,通过使用小根堆维护并找到代价最小的两对进行合并,适用于解决特定类型的组合优化问题。代码采用C++实现,并详细展示了从输入到输出的完整流程。

点击进入幻想郷


日常水题
贪心策略:每次找代价最小的两对合并,用小根堆来维护,每次合并之后将当前合并结果重新推入队列,直到合并完成(n-1次)

代码如下

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <queue>

using namespace std;
typedef long long LL;

LL n;
LL tot,ans;
priority_queue<LL ,vector<LL >,greater<LL > >q;

int main()
{
    scanf("%lld",&n);
    for(LL i = 1;i <= n;i++)
    {
        LL aa;
        scanf("%lld",&aa);
        q.push(aa);
    }
    while(q.size() != 1)
    {
        LL u = q.top();
            q.pop();
        LL v = q.top();
            q.pop();
        //cout<<"tot_after : "<<tot<<endl;
        tot = u+v;
        //cout<<"tot_fin : "<<tot<<endl;
        ans += tot;
        q.push(tot);
        //cout<<"ans : "<<ans<<endl;
    }
    printf("%lld\n",ans);

return 0;
}

THE END

By Peacefuldoge

http://blog.youkuaiyun.com/loi_peacefuldog

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值