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;
}