锯木 (cut.c/cpp/pas)
【题目描述】
LazyChild需要将一根非常长的木棒切成n段,每段的长度分别为L1,L2,…,LN个长度单位。∑Li(I= 1,2,…,N)恰好就是原木棒的长度。我们认为切割时仅在整数点处切且没有木材损失。
LazyChild发现,每一次切割花费的体力与该木棒的长度成正比,不妨设切割长度为1的木棒花费1单位体力。
LazyChild想请你帮他计算出最少要多少体力。
【输入文件】
第一行一个整数n。
第二行n个整数,分别表示L1,L2,…,LN。
【输出文件】
一行一个整数表示,LazyChild要付出的最少体力值。
【样例输入】
4
3 5 7 11
【样例输出】
49
【数据规模和约定】
对于30%的数据,n <= 10
对于100%的数据,n <= 100000,Li<= 1000
正着来没试过,但是一定是有反例的。
但是反过来考虑是果子合并,这样贪心就比较合理
#include <cstdio>
#include <vector>
#include <iostream>
#include <functional>
#include <queue>
using std::cout;
using std::greater;
using std::vector;
using std::priority_queue;
typedef long long ll;
priority_queue<ll,vector<ll>,greater<ll> > heap;
long getint()
{
long rs=0;bool sgn=1;char tmp;
do tmp = getchar();
while (!isdigit(tmp)&&tmp-'-');
if (tmp == '-'){tmp=getchar();sgn=0;}
do rs=(rs<<3)+(rs<<1)+tmp-'0';
while (isdigit(tmp=getchar()));
return sgn?rs:-rs;
}
int main()
{
freopen("cut.in","r",stdin);
freopen("cut.out","w",stdout);
long n = getint();
for (long i=1;i<n+1;i++)
{
heap.push(getint());
}
ll ans = 0;
for (long i=1;i<n;i++)
{
long a = heap.top();
heap.pop();
long b = heap.top();
heap.pop();
ans += a+b;
heap.push(a+b);
}
cout << ans;
return 0;
}