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

题意:

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

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值