POJ3253 Fence Repair(Huffman)

POJ 3253 http://poj.org/problem?id=3253

 

题目大意:将一节树枝折断成两节,均会产生与树枝长度相等的费用,问最低费用是多少。

 

样例解释:

sorted: 5, 8, 8 (greater)
first: 5 + 8 = 13, ans = 13;
second: 13 + 8 = 21, ans = 13 + 21 = 34;

cout << 34 << endl;

 

解题思路:

排序后,最小和次小的首先整合成一段更大的木头,再将这段整合后的木头插入到适当的位置(注意 不能是无序直接插入)

再依次重复,直到队列中只剩下一个数据。

即Huffman Tree (哈夫曼树、最优二叉树)

(图片来自百度百科https://baike.baidu.com/item/哈夫曼树/2305769?fr=aladdin

 

针对到这题,采用优先队列来解决。

知识速览:


priority_queue <node> q;
//node是一个结构体
//结构体里重载了‘<’小于符号
priority_queue <int,vector<int>,greater<int> > q;
//不需要#include<vector>头文件
//注意后面两个“>”不要写在一起,“>>”是右移运算符
priority_queue <int,vector<int>,less<int> >q;

q.size();//返回q里元素个数
q.empty();//返回q是否为空,空则返回1,否则返回0
q.push(k);//在q的末尾插入k
q.pop();//删掉q的第一个元素
q.top();//返回q的第一个元素
q.back();//返回q的末尾元素

AC代码:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <set>
#include <queue>
#include <vector>
using namespace std;
typedef long long ll;
const int MAX = 20005;
const int enf = 0x3f3f3f;
ll pos[MAX];
int main() {
    int n;
    cin >> n;
    priority_queue<int, vector<int>, greater<int> > q;
    for(int i = 0; i < n; i++) {
        cin >> pos[i];
        q.push(pos[i]);
    }

    ll ans = 0;
    while(q.size() > 1) {
        ll x1 = q.top();
        q.pop();
        ll x2 = q.top();
        q.pop();
        ll x = x1 + x2;
        ans += x;
        q.push(x);
    }

    cout << ans << endl;

    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值