首页 > 代码库 > POJ 3253-Fence Repair(堆)

POJ 3253-Fence Repair(堆)

Fence Repair
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 27055 Accepted: 8800

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 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
哈曼夫树。
题意 :把一根长度为x的木板切成n段,每段的长度已给出来,切某块木板时,花费的费用为该木板的长度,一开始以为只要每次选出最长的木板然后从总的中切掉就是最小花费,实际上不是,其实用脑子想想也知道了,如果总长很长的话,而需要的木板的长度又很小,每次从总长中切掉花费将会很大,所以这种思路是不对的,看了讨论区才明白,我们可以把切这个过程逆回去,就是把这n段木板连接起来,每次花费的钱为待连接的两段木板的长度,(仔细想想,切跟连花费的钱是相同的,即是等价的,画一下图可以看出来) 然后有一种思想是:初始化一个最小堆,每次从堆中选出最小的两段木板进行连接,连接完之后在放入到堆中。总共n-1次连接即可
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cctype>
#include <cmath>
#include <cstdlib>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <list>
#define ll long long
using namespace std;
const int INF = 0x3f3f3f3f;
ll a[20010];
int main()
{
	int n;
	while(~scanf("%d",&n))
	{
		for(int i=0;i<n;i++)
			scanf("%lld",a+i);
		make_heap(a,a+n,greater<int>());
		int t=n-1;ll ans=0,tem;
		while(t--)
		{
			tem=a[0];pop_heap(a,a+n,greater<int>());--n;
			tem+=a[0];pop_heap(a,a+n,greater<int>());--n;
			ans+=tem;a[n++]=tem;
			push_heap(a,a+n,greater<int>());
		}
		printf("%lld\n",ans);
	}
	return 0;
}



POJ 3253-Fence Repair(堆)