Fence Repair(POJ-3253)
Problem Description
Farmer 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 theN 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 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 theN 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 1: One integer N, the number of planks
Lines 2..N+1: Each line contains a single integer describing the length of a needed plank
Output
Line 1: One integer: the minimum amount of money he must spend to makeN-1 cuts
Sample Input
3
8
5
8
Sample Output
34
題意:要把一個木板截成給定長度的幾塊小木板,每一次費用是當前木板的長度,給出要截成的小木板的個數(shù) n 與長度,求最小花費。
思路:根據(jù)貪心思想,要使費用最小,就要讓每次鋸成的兩塊木板的長度和最小。使用優(yōu)先隊列,每次選擇最小的兩塊木頭相加,相加后再次進入隊列,再選擇最小的兩塊木頭相加,依次類推,直至隊列為空取得最小值。
Source Program
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<string> #include<cstdlib> #include<queue> #include<set> #include<map> #include<stack> #include<vector> #define INF 0x3f3f3f3f #define PI acos(-1.0) #define N 10001 #define MOD 123 #define E 1e-6 using namespace std; priority_queue < int,vector<int>,greater<int> > q;//最小值優(yōu)先的優(yōu)先隊列 int main() {int n;scanf("%d",&n);for(int i=0;i<n;i++){int temp;scanf("%d",&temp);q.push(temp);}long long sum=0;while(n!=1)//共截取n-1次{int a,b;a=q.top();//取隊首元素q.pop();//隊首元素出隊b=q.top();//取隊首元素q.pop();//隊首元素出隊sum+=a+b;//記錄花費q.push(a+b);//隊列中最小值與次小值的和入隊n--;}printf("%lld\n",sum);return 0; }?
總結(jié)
以上是生活随笔為你收集整理的Fence Repair(POJ-3253)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 出现次数超过一半的数(信息学奥赛一本通-
- 下一篇: Game of Lines(POJ-36