Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 27841 | Accepted: 9050 |
Description
Farmer John wants to repair a small length of the fence around the pasture. He measures the fence and finds that he needs N (1 ≤ N ≤ 20,000) planks of wood, each having some integer length Li (1 ≤ Li ≤ 50,000) units. He then purchases a single long board just long enough to saw into the N planks (i.e., whose length is the sum of the lengths Li). FJ is ignoring the "kerf", the extra length lost to sawdust when a sawcut is made; you should ignore it, too.
FJ sadly realizes that he doesn't own a saw with which to cut the wood, so he mosies over to Farmer Don's Farm with this long board and politely asks if he may borrow a saw.
Farmer Don, a closet capitalist, doesn't lend FJ a saw but instead offers to charge Farmer John for each of the N-1 cuts in the plank. The charge to cut a piece of wood is exactly equal to its length. Cutting a plank of length 21 costs 21 cents.
Farmer Don then lets Farmer John decide the order and locations to cut the plank. Help Farmer John determine the minimum amount of money he can spend to create the N planks. FJ knows that he can cut the board in various different orders which will result in different charges since the resulting intermediate planks are of different lengths.
Input
Lines 2.. N+1: Each line contains a single integer describing the length of a needed plank
Output
Sample Input
3 8 5 8
Sample Output
34
Hint
The original board measures 8+5+8=21. The first cut will cost 21, and should be used to cut the board into pieces measuring 13 and 8. The second cut will cost 13, and should be used to cut the 13 into 8 and 5. This would cost 21+13=34. If the 21 was cut into 16 and 5 instead, the second cut would cost 16 for a total of 37 (which is more than 34).
题意:
将一段木棒切割成固定的长度,每次切割的花费都等于所切割的那段木棒的长度,如题意,cost(8,5,8)=(8+5)+(8+5+8);求怎样切割花费最少,计算最小花费。
思路:
逆推,每次都找到最短与次短的两根,将其视为此次切割的结果,而此次的花费是两段长度的总和,也是所有情况中最小的,算法证明很容易得出这样能得到最优的解决方案;注意保存的长度要设为长整形,每次如何找到最小的两根是关键,每次调用sort会超时;
代码如下:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <cstring>
#include <algorithm>
using namespace std;
#define MAX_N 20010
long long length;//总长度
int N;
int L[MAX_N];//储存长度
int main()
{
cin>>N;
for(int i=0;i<N;i++)
cin>>L[i];
length=0;
while(N>1)
{
int x1=0;//x1保存最小的,初始化为0
int x2=1;//x2保存次小的,初始化为1
if(L[x1]>L[x2])
swap(x1,x2);//利用swap交换x1,x2的值
for(int i=2;i<N;i++)
{
if(L[i]<L[x1])//小于最小的
{
x2=x1;
x1=i;
}
else if(L[i]<L[x2])//小于次小的
{
x2=i;
}
}
length+=(L[x1]+L[x2]);//加上此次的花费
//将新的长度x1+x2放入数组,删掉最后一个,但是要考虑x1或x2即为最后一个的情况
if(x1==N-1)
swap(x1,x2);
L[x1]+=L[x2];
L[x2]=L[N-1];
N--;//长度--
}
cout<<length<<endl;
return 0;
}