#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;
}
}
手写堆
最新推荐文章于 2025-02-11 02:41:03 发布