修理牧场(25)
时间限制
400 ms
内存限制
32000 kB
代码长度限制
8000 B
判题程序
Standard
农夫要修理牧场的一段栅栏,他测量了栅栏,发现需要N块木头,每块木头长度为整数Li个长度单位,于是他购买了一条很长的、能锯成N块的木头,即该木头的长度是Li的总和。
但是农夫自己没有锯子,请人锯木的酬金跟这段木头的长度成正比。为简单起见,不妨就设酬金等于所锯木头的长度。例如,要将长度为20的木头锯成长度为8、7和5的三段,第一次锯木头花费20,将木头锯成12和8;第二次锯木头花费12,将长度为12的木头锯成7和5,总花费为32。如果第一次将木头锯成15和5,则第二次锯木头花费15,总花费为35(大于32)。
请编写程序帮助农夫计算将木头锯成N块的最少花费。
输入格式说明:
输入首先给出正整数N(<=104),表示要将木头锯成N块。第2行给出N个正整数(<=50),表示每段木块的长度。
输出格式说明:
输出一个整数,即将木头锯成N块的最少花费。
样例输入与输出:
序号 | 输入 | 输出 |
1 | 8 4 5 1 2 1 3 1 1 | 49 |
2 | 1 1 | 0 |
正确代码(1):
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <iostream>
using namespace std;
class cmp{
public:
bool operator()(const int a,const int b) const{
return a>b;
}
};
int main(){
int n,a,b,sum=0;
priority_queue<int,vector<int>,cmp> q;
cin>>n;
while(n--){
scanf("%d",&a);
q.push(a);
}
while(q.size()>1){
a=q.top();q.pop();
b=q.top();q.pop();
sum+=a+b;q.push(a+b);
}
printf("%d\n",sum);
return 0;
}
代码(2)(与上面做法一样,只是写法不一样):
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <iostream>
using namespace std;
int main(){
int n,a,b,sum=0;
priority_queue<int,vector<int>,greater<int> > q;
cin>>n;
while(n--){
scanf("%d",&a);
q.push(a);
}
while(q.size()>1){
a=q.top();q.pop();
b=q.top();q.pop();
sum+=a+b;q.push(a+b);
}
printf("%d\n",sum);
return 0;
}
代码(3)(用数组模拟):
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <iostream>
using namespace std;
int a[20500];
int main(){
int n,i,j,sum=0,ans=0;
cin>>n;
for(i=0;i<n;i++)
scanf("%d",&a[i]);
sort(a,a+n);
for(i=0;i<n-1;i++){
sum=a[i]+a[i+1];
ans+=sum;
for(j=i+2;j<n;j++){
if(sum>a[j])
a[j-1]=a[j];
else{
a[j-1]=sum;break;
}
}
if(j==n)
a[j-1]=sum;
}
printf("%d\n",ans);
return 0;
}