Fence Repair(poj3253)
Posted zjl192628928
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Fence Repair(poj3253)相关的知识,希望对你有一定的参考价值。
题目链接:http://poj.org/problem?id=3253
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).
给定各个要求的小木板的长度,及小木板的个数n,求最小费用
提示:
以
3
8
8
5为例:
先从无限长的木板上锯下长度为 21 的木板,花费 21
再从长度为21的木板上锯下长度为5的木板,花费5
再从长度为16的木板上锯下长度为8的木板,花费8
总花费 = 21+5+8 =34
解题思路:由于木板的切割顺序不确定,自由度很高,这个题目貌似很难入手。但是其实可以用略微奇特的贪心法来求解。利用Huffman思想,要使总费用最小,那么每次只选取最小长度的两块木板相加,再把这些“和”累加到总费用中即可。
附上代码:
1 #include<iostream> 2 using namespace std; 3 typedef long long ll; 4 int l[20020]; 5 int main() 6 { 7 int n; 8 while(cin>>n) 9 { 10 ll ans=0; 11 for(int i=0;i<n;i++) cin>>l[i]; 12 //直到计算到木板为1是为止 13 while(n>1) 14 { 15 //求出最短的木板x和次短的木板 y 16 int x=0,y=1; 17 if(l[x]>l[y]) swap(x,y); 18 for(int i=2;i<n;i++) 19 { 20 if(l[i]<l[x]){ 21 y=x; 22 x=i; 23 } 24 else if(l[i]<l[y]){ 25 y=i; 26 } 27 } 28 //将两块最短的板合并 29 int t=l[x]+l[y]; 30 ans+=t; 31 if(x==n-1) swap(x,y); 32 l[x]=t; 33 l[y]=l[n-1]; 34 n--; 35 } 36 cout<<ans<<endl; 37 } 38 return 0; 39 }
以上是关于Fence Repair(poj3253)的主要内容,如果未能解决你的问题,请参考以下文章