POJ(3253) Fence Repair
Descriptions:
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:
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 cuts
Sample input:
3
8
5
8
Sample output:
34
思路:
贪心算法。哈夫曼树。
具体思路:
- 将L1~LN排序
- 取出最短的两个节点,将其合并
- 重新排序,回到步骤二
在计算的时候大致有两种方法:
- 暴力解法,时间复杂度O(N2)
- 构建优先队列,时间复杂度O(N*logN)
代码:
#include<iostream>
#include<queue>
#define MAX_N 20000
using namespace std;
int N, L[MAX_N];
void init() {
cin >> N;
for (int i = 0; i < N; i++) {
cin >> L[i];
}
}
void solve() { //暴力解法
init();
__int64 ans = 0; //不使用__int64将会WA
while (N > 1) {
int min = 0, smin = 1;
if (L[min] > L[smin])
swap(min, smin);
for (int i = 2; i < N; i++) {
if(L[i] < L[min]) {
smin = min; //This statement is important!
min = i;
}
else if(L[i] < L[smin])
smin = i;
}
int t = L[min] + L[smin];
ans += t;
if (min == N-1)
swap(min, smin);
L[min] = t;
L[smin] = L[N - 1];
N--;
}
cout << ans << endl;
}
void solve2() { //优先队列
init();
__int64 ans = 0;
int t; //to store the sum of the two p.top()
priority_queue<int, vector<int>, greater<int> > P;
for (int i = 0; i < N; i++)
P.push(L[i]);
while (P.size() != 1) {
t = 0;
t += P.top();
P.pop();
t += P.top();
P.pop();
P.push(t);
ans += t;
}
cout << ans << endl;
}
int main()
{
solve2();
return 0;
}
注意:
结果一定要使用__int64
,不然就会WA。