手写堆

#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 1e3 + 10;
struct Heap {
    int heap[MAX_N];
    int pos[MAX_N];
    int size;
    void init() {
        size = 0;
    }
    void push(int a) {
        heap[++size] = a;
        pos[a] = size;
        swim(size);
    }
    void pop() {
        heap[1] = heap[size--];
    //  cout << " check =  "<<heap[1] <<endl;
        pos[heap[1]] = 1;
        sink(1);
    }
    void erase(int a) {
        heap[pos[a]] = heap[size--];
        pos[heap[pos[a]]] = pos[a];
        sink(pos[a]);
    }
    void swim(int x) {
        for (int i = x; i; i >>= 1) {
            int f = i >> 1;
            if (heap[f] > heap[i]) {
                swap(pos[heap[f]], pos[heap[i]]);
                swap(heap[f], heap[i]);
            }
            else {
                break;
            }
        }
    }
    void sink(int x) {
        for (int i = x; i <= size; i <<= 1) {
            int c = i << 1;
            if( c > size) break ; 
            if (c <= size && c + 1 <= size && heap[c] > heap[c + 1]) {
                c++;
            }
            if (heap[i] > heap[c]) {
                swap(pos[heap[i]], pos[heap[c]]);
                swap(heap[i], heap[c]);
            }
            else {
                break;
            }
        }
    }
} a ;

int main(){
    a.push(5); a.push(3); a.push(2) ; a.push(1) ;
    a.erase(3);
    for(int i = 1 ; i <= a.size ; i ++){
        cout <<" i  = " << i <<" " <<a.heap[i] <<endl; 
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值