poj 3253 Fence Repair (STL優先隊列)
vasttian https://blog.csdn.net/u012860063/article/details/34805369
轉載請註明出處:http://blog.csdn.net/u012860063
題目鏈接: id=3253" rel="nofollow">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 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
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 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 make?N-1 cutsSample Input
3 8 5 8
Sample Output
34
Hint
He wants to cut a board of length 21 into pieces of lengths 8, 5, and 8.?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).
Source
field=source&key=USACO+2006+November+Gold" rel="nofollow" style="text-decoration:none;">USACO 2006 November Gold
題意:
有一位農夫要把一個木板(長度為 N 塊木板長度之和)使用 (N-1) 次鋸成 N 塊給定長度的小木板,每次鋸都要收取一定費用,
這個費用就是當前鋸的這個木板的長度,
給定各個要求的小木板的長度,及小木板的個數? N。求最小的費用;
PS:
以
3
8 5 8為例:
先鋸長度為?21?的木板使其為 13 和 8 的兩塊木板,花費?21
再從長度為?13?的木板上鋸下長度為?8 和 5?的兩塊木板,花費?13
總花費?: 21 + 13 = 34
假設第一次鋸下 16 和 5,第二次鋸下 8 和 8 。總花費:21 + 16 = 37
思路:
要使總費用最小。那麽每次僅僅選取最小長度的兩塊木板相加,再把這些“和”累加到總費用中就可以;
代碼例如以下:
/*STL 優先隊列*/
#include <cstdio>
#include <queue>
#include <vector>
#include <iostream>
using namespace std;
int main()
{
int n;//須要分割的木板個數
__int64 temp,a,b,mincost;
while(~scanf("%d",&n))
{
//定義從小到大的優先隊列,可將greater改為less。即為從大到小
priority_queue<int, vector<int>, greater<int> > Q;
while(!Q.empty())//清空隊列
Q.pop();
for(int i = 1; i <= n; i++)
{
scanf("%I64d",&temp);
Q.push(temp);//輸入要求的木板長度(費用)並入隊
}
mincost = 0;//最小費用初始為零
while(Q.size() > 1)//當隊列中小於等於一個元素時跳出
{
a = Q.top();//得到隊首元素的值,並使其出隊
Q.pop();
b = Q.top();//兩次取隊首。即得到最小的兩個值
Q.pop();
Q.push(a+b);//把兩個最小元素的和入隊
mincost +=a+b;
}
printf("%I64d\n",mincost);
}
return 0;
}
poj 3253 Fence Repair (STL優先隊列)