Pagini recente » Cod sursa (job #3163071) | Cod sursa (job #1046871) | Cod sursa (job #1454137) | Cod sursa (job #2037792) | Cod sursa (job #1535863)
#include <iostream>
#include <string.h>
using namespace std;
const int nmax = 200010;
int v[nmax], heap[nmax], pos[nmax], nr = 0, len = 0, root = 0;
inline int father(int x) { return x / 2; };
inline int left (int x) { return x * 2 ; };
inline int right (int x) { return x * 2 + 1; };
void ins(int val);
void del(int ind);
int main(){
freopen("heapuri.in", "r", stdin);
freopen("heapuri.out", "w", stdout);
int m,x,a;
scanf("%d ", &m);
for (; m--;) {
scanf("%d", &x);
switch (x)
{
case 1:
scanf("%d", &a);
ins(a);
break;
case 2:
scanf("%d", &a);
del(a);
break;
case 3:
printf("%d \n", v[heap[1]]);
break;
}
}
fclose(stdin);
fclose(stdout);
return 0;
}
void ins(int val){
v[++nr] = val;
heap[++len] = nr;
pos[nr] = len;
int x = len;
while (v[heap[x]] < v[heap[father(x)]] && x > 1) {
swap(heap[x], heap[father(x)] );
pos[heap[x]] = x;
pos[heap[father(x)]] = father(x);
x = father(x);
}
}
void del(int iedik) {
v[iedik] = -1;
heap[pos[iedik]] = heap[len];
pos[heap[len--]] = pos[iedik];
int x = pos[iedik]; // index of the swaped number
//going up
while (v[heap[x]] < v[heap[father(x)]] && x > 1) {
swap(heap[x], heap[father(x)]);
pos[heap[x]] = x;
pos[heap[father(x)]] = father(x);
x = father(x);
}
// going down
bool q = true;
while (q && left(x) <= len) {
q = false;
if (right(x) <= len) {
if (v[heap[left(x)]] < v[heap[right(x)]] && v[heap[left(x)]] < v[heap[x]] ) {
swap(heap[left(x)], heap[x]);
pos[heap[x]] = x;
pos[heap[left(x)]] = left(x);
x = left(x);
q = true;
}
else if (v[heap[right(x)]] < v[heap[x]]) {
swap(heap[right(x)], heap[x]);
pos[heap[x]] = x;
pos[heap[right(x)]] = right(x);
x = right(x);
q = true;
}
}
else if (v[heap[x]] > v[heap[left(x)]]) {
swap(heap[left(x)], heap[x]);
pos[heap[x]] = x;
pos[heap[left(x)]] = left(x);
x = left(x);
q = true;
}
}
}