记录一个菜逼的成长。。
题目链接
题目大意:
将一块长度为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;
}