链接:点击打开链接
题目大意:FJ需要修补牧场的围栏,他需要 N 块长度为 Li 的木头(N planks of woods)。开始时,FJ只有一块无限长的木板,因此他需要把无限长的木板锯成 N 块长度
为 Li 的木板,Farmer Don提供FJ锯子,但必须要收费的,收费的标准是对应每次据出木块的长度,比如说测试数据中 5 8 8,一开始,FJ需要在无限长的木板上锯下长度 21 的木板(5+8+8=21),第二次锯下长度为 5 的木板,第三次锯下长度为 8 的木板,至此就可以将长度分别为 5 8 8 的木板找出
题目可以转化为Huffman树构造问题 :
给定 N planks of woods,
1. 在 N planks 中每次找出两块长度最短的木板,然后把它们合并,加入到集合A中,
2. 在集合中找出两块长度最短的木板,合并加入到集合A中,重复过程,直到集合A中只剩下一个元素
显然,通过每次选取两块长度最短的木板,合并,最终必定可以合并出长度为 Sum(Li)的木板,并且可以保证总的耗费最少
#include<iostream>
#include<cstdio>
#include<queue>
#include<vector>
using namespace std;
struct cmp{
bool operator()(int &a,int &b){
return a>b;
}
};
int main(){
int i,n,m,x,y;
priority_queue<int,vector<int>,cmp>q;
__int64 sum;
while(~scanf("%d",&n)){
for(i=0;i<n;i++){
scanf("%d",&m);
q.push(m);
}
sum=0;
while(q.size()!=1){
x=q.top();
q.pop();
y=q.top();
q.pop();
sum+=(x+y);
q.push(x+y);
}
printf("%I64d\n",sum);
}
return 0;
}