CodeVS 1063 合并果子

http://codevs.cn/problem/1063/

堆结构的上手测试题。

之前学堆的时候写过一个模板,直接拿过来用。

#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
int heap[20010] , temp ,size , ans , n , a , b;
void Insert(int x){
    int curr = ++size;
    heap[size] = x;
    int parent = curr / 2;
    while(parent > 0 && heap[parent] > heap[curr]){
        swap(heap[parent] , heap[curr]);
        curr = parent;
        parent = curr / 2;
    }     
}
void Pop(){
    heap[1] = heap[size--];
    int curr = 1;
    int son = curr * 2;
    if(heap[son] > heap[son + 1])son++;
    while(son <= size && heap[son] < heap[curr]){
        swap(heap[son] , heap[curr]);
        curr = son;
        son = curr * 2;
        if(heap[son] > heap[son + 1])son++;
    }
}

每次把小根堆里最小的两个值Pop出来,再Insert二者的和,来模拟合并两堆果子。最后只剩一堆的时候停止。

主函数:

int main(){
    cin >> n;
    for(int i = 1 ; i <= n ; i++){
        cin >> temp;
        Insert(temp);
    }
    while(size > 1){
        a = heap[1];Pop();
        b = heap[1];Pop();
        temp = a + b;
        Insert(temp);
        ans += temp;
    }
    cout << ans << endl;
    return 0;
}

转载于:https://www.cnblogs.com/miserweyte/p/11134368.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值