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
Output
Sample Input
3 8 5 8
Sample Output
34
Hint
题意:
将一段木棒切割成固定的长度,每次切割的花费都等于所切割的那段木棒的长度,如题意,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;
}
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- niushuan.com 版权所有 赣ICP备2024042780号-2
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务