poj-3253 Fence Repair(哈夫曼树)

来源:互联网 发布:淘宝如何收费标准 编辑:程序博客网 时间:2024/05/16 11:01
Fence Repair
Time Limit:2000MS     Memory Limit:65536KB
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

题意:农夫买来长木板锯成想要的长度,找守财奴借锯子,守财奴要求每锯一次收取与被锯断的木头长度等同的费用,给你需要的木头长度,求最小费用。

思路:自然是长度大的木头越快锯出来越好,实际上便是带权路径长度和最小的哈夫曼树。

            给出两种解法,优先队列和二叉堆的小根堆。

//二叉堆,小根堆//Memory 268 KB Time 32 ms#include<iostream>#include<stdio.h>using namespace std;#define maxn 20010#define ll __int64ll n,len;ll p[maxn];void heap_insert(ll k)//将k插入堆尾,并维护性质{ll t=++len;p[t]=k;while(t>1){if(p[t/2]>p[t]){//小值自下而上冒泡swap(p[t],p[t/2]);t/=2;}else break;}}void heap_pop()//取小根堆的堆首元素,并维护性质{ll t=1;p[1]=p[len--];while(t*2<=len){ll k=t*2;if(k<len&&p[k+1]<p[k]) k++;//取左右儿子中值较小的if(p[t]>p[k]){//大值向下调整swap(p[t],p[k]);t=k;}else break;}}int main(){scanf("%I64d",&n);    len=0;for(ll i=1;i<=n;i++){scanf("%I64d",&p[i]);heap_insert(p[i]);}ll ans=0;while(len>1){ll a,b;a=p[1];heap_pop();b=p[1];heap_pop();ans+=a+b;heap_insert(a+b);}printf("%I64d\n",ans);return 0;}

//优先队列//Memory 444 KB Time 16 ms#include<iostream>#include<stdio.h>#include<queue>#include<vector>#define ll __int64using namespace std;priority_queue<ll,vector<ll>,greater<ll> >que;int main(){ll n,i,x,y,ans=0;scanf("%I64d",&n);for(i=1;i<=n;i++){scanf("%I64d",&x);que.push(x);}while(--n){x=que.top();que.pop();y=que.top();que.pop();x+=y;ans+=x;que.push(x);}printf("%I64d\n",ans);return 0;}


0 0
原创粉丝点击