您的位置:首页 > Web前端

poj 3253 Fence Repair(哈夫曼+二叉堆)

2015-07-07 23:28 393 查看
题意:

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).

这题参考大神的思路写的 本来想添加大神的博文链接 突然找不到了

解题思路 :

首先方法就是哈夫曼的原理,每次从序列中找出两个最小的相加把这个值累加到ans中 并把这个值放入序列中重复循环直到只有一个元素为止

如果按照原来的哈夫曼的原理每次取最小的两个元素利用排序会超时

所以利用二叉堆

1.把所有元素建成一个最小堆

2.取出堆顶元素(最小元素)并保存既得到第一个最小元素,将最后一个元素移入堆顶的位置,进行堆调整得到新的最小堆

3 .再取出堆顶元素就得到第二个最小元素

4.将得到的两个元素相加放入堆顶并累加到ans,再次调整得到新堆

5.重复以上步骤2.3.4 直到堆里只有1个元素

代码:

#include "stdio.h"

#include "stdlib.h"

long int ss[20000];

void heapfix(long
int a,long
int b)
{

long i,j,temp;
temp=ss[a];
i=a;
j=2*a;

while(j<=b)
{

if(j+1<=b&&ss[j+1]<ss[j]) j++;

if(ss[j]<temp) {

ss[i]=ss[j];
i=j;
j=j*2;
}

else break;
}

ss[i]=temp;
}

int main()
{

long long
int n,ans=0;

scanf("%lld",&n);

for(int i=1;i<=n;i++)

scanf("%ld",&ss[i]);

for(long
int i=n/2;i>=1;i--)

heapfix(i, n);

while(n>1)
{

ss[0]=ss[1];

ss[1]=ss[n--];

heapfix(1,n);

ss[1]+=ss[0];
ans+=ss[1];

heapfix(1,n);
}

printf("%lld\n",ans);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: