poj 3253(Fence Repair)

发布时间:2026/7/28 14:48:53

poj 3253(Fence Repair) DescriptionFarmer John wants to repair a small length of the fence around the pasture. He measures the fence and finds that he needsN(1 ≤N≤ 20,000) planks of wood, each having some integer lengthLi(1 ≤Li≤ 50,000) units. He then purchases a single long board just long enough to saw into theNplanks (i.e., whose length is the sum of the lengthsLi). 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 doesnt own a saw with which to cut the wood, so he mosies over to Farmer Dons Farm with this long board and politely asks if he may borrow a saw.Farmer Don, a closet capitalist, doesnt lend FJ a saw but instead offers to charge Farmer John for each of theN-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 theNplanks. 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.InputLine 1: One integerN, the number of planksLines 2..N1: Each line contains a single integer describing the length of a needed plankOutputLine 1: One integer: the minimum amount of money he must spend to makeN-1 cutsSample Input3 8 5 8Sample Output34HintHe wants to cut a board of length 21 into pieces of lengths 8, 5, and 8.The original board measures 85821. 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 211334. 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).思路类似霍夫曼编码将最小的板子和次最小的板子相加L1L2L3L4.....Ln再对这n-1个值进行一次最小值和次最小值的相加直到只剩下1个板子数为止。#includestdio.h #includestdlib.h #includealgorithm #includestring.h using namespace std; int n; long long ans0,L[20001]; int main() { scanf(%d,n); for(int i0;in;i) scanf(%lld,L[i]); while(n1) { int mii10,mii21; if(L[mii1]L[mii2]) swap(mii1,mii2); for(int i2;in;i)//寻找最小值和次最小值 { if(L[i]L[mii1]) { mii2mii1; mii1i; } else if(L[i]L[mii2]) mii2i; } long long tL[mii1]L[mii2]; anst; if(mii1n-1) swap(mii1,mii2);//因为下一句的赋值原因防止L[mii1]L[mii2]L[n-1] L[mii1]t; L[mii2]L[n-1]; n--; } printf(%lld\n,ans); }

相关新闻