【POJ3253】Fence Repair(优先队列+贪心)

记录一个菜逼的成长。。

题目链接
题目大意:
将一块长度为L的木板切割为两块,花费为L,切割后的两块木板的长度和为切割前的长度。给你N个切割后的木板的长度,问最小花费是多少。

书上的一道贪心题。用huffman编码的思想贪心,感觉挺有趣的。
我们可以考虑将两块合并成一块木板,花费为合并后的木板的长度。
根据huffman思想,每次选取长度最小的两个合并,以此贪心,最后可以保证花费最少。

如何选取最小的两个,可以使用优先队列。

#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
typedef long long LL;
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n;
    while(cin>>n){
        priority_queue<int,vector<int>,greater<int> >q;
        LL ans = 0;
        for( int i = 0; i < n; i++ ){
            int x;cin>>x;
            q.push(x);
        }
        while(q.size() > 1){
            int x = q.top();q.pop();
            x += q.top();q.pop();
            ans += (LL)x;
            q.push(x);
        }
        cout<<ans<<endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值