POJ 3253 Fence Repair
Enter
Description
Farmer John wants to repair a small length of the fence around the pasture. He measures the fence and finds that he needs planks of wood, each having some integer length units. He then purchases a single long board just long enough to saw into the planks (i.e., whose length is the sum of the lengths ). 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 cuts in the plank. The charge to cut a piece of wood is exactly equal to its length. Cutting a plank of length costs 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
Line : One integer , the number of planks
Lines to : Each line contains a single integer describing the length of a needed plank
Output
Line : One integer: the minimum amount of money he must spend to make cuts
Sample Input
3
8
5
8
Sample Output
34
Hint
He wants to cut a board of length into pieces of lengths , and .
The original board measures . The first cut will cost , and should be used to cut the board into pieces measuring and . The second cut will cost , and should be used to cut the into and . This would cost . If the was cut into and instead, the second cut would cost for a total of (which is more than ).
Translation
我们要将将一根很长的木条切成 份,每份的长度为 ,未切割前木条的长度为 。每次切断木条时,需要的开销为这根木条的长度,如将一根长度为 的木条分割成 和 的两部分,开销为 。请求出按照目标要求将模板切割完最小的开销是多少。
Idea
如果我们需要将一根木条分成长度为 的两份,那么开销就是 ,我们可以定义将两根长度为 的木条拼成一根的开销也为 。对于题目的情境,每一次将某一根木条切成两根的开销,相当于将两根木条合并成一根。因此,可以将题目看成是把 段木条拼成一根,每次拼的代价为所拼木条的长度和。
显然,越早拼好的木条其产生开销的机会就越多。例如有三根木条长度分别为 ,如果选择先拼 ,那么产生的总开销为 。因此贪心的策略是每次选取两个最小的来拼,可以用优先队列实现。时间复杂度为
Code
1 |
|