个人模板 堆

大顶堆

#include <bits/stdc++.h>
using namespace std;

const int N = 1e5 + 10;
struct heap{
    int size, a[N<<1];

    heap(){
        size = 0;
        memset(a, 0, sizeof(a));
    }

    void Pushup(int k){
        while(k > 1){
            if(a[k] > a[k>>1]){
                swap(a[k], a[k>>1]);
            }
            k >>= 1;
        }
    }

    void Pushdown(int k){
        while(k<<1 <= size){
            int kk = k<<1;
            if(kk < size && a[kk] < a[kk+1]){
                kk++;
            }
            if(a[k] < a[kk]){
                swap(a[k], a[kk]);
                k = kk;
            }
            else return;
        }
    }

    void push(int k){
        a[++size] = k;
        Pushup(size);
    }

    void pop(){
        swap(a[1], a[size]);
        size--;
        Pushdown(1);
    }

    int top(){
        return a[1];
    }

    bool empty(){
        return size;
    }
};

int main(){
    heap k;
    int a[6] = {1, 4, 2, 6, 3, 9};
    for(int i = 0; i < 6; i++){
        k.push(a[i]);
    }
    printf("top = %d\n", k.top());
    k.pop();
    printf("top = %d\n", k.top());
    k.push(8);
    printf("top = %d\n", k.top());
}
#include <bits/stdc++.h>
using namespace std;

vector<int> k;

bool cmp(int a, int b){
    return a < b;
}

int main(){
    int a[6] = {1, 4, 2, 9, 6, 3};
    for(int i = 0; i < 6; i++){
        k.push_back(a[i]);
    }
    make_heap(k.begin(), k.end(), cmp);
    cout << "top = " << k[0] << endl;
    pop_heap(k.begin(), k.end(), cmp);
    cout << "top = " << k[0] << endl;
    k.push_back(8);
    push_heap(k.begin(), k.end(), cmp);
    cout << "top = " << k[0] << endl;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值