Pagini recente » Cod sursa (job #1905000) | Cod sursa (job #252405) | Cod sursa (job #430492) | Cod sursa (job #550357) | Cod sursa (job #2353613)
#include <stdio.h>
#include <iostream>
using namespace std;
const int NMAX = 200005;
int heap[NMAX];
int pos[NMAX];
int A[NMAX];
int L = 0;
int contor = 0;
int N, Q;
void swap(int x, int y) {
int tmp = heap[x];
heap[x] = heap[y];
heap[y] = tmp;
// check x vs y her
pos[heap[x]] = x;
pos[heap[y]] = y;
}
void heapify_down(int ix) {
int l = ix * 2;
int r = ix * 2+1;
while (ix <= L && l <= L) {
int min_cand = l;
if (r <= L && A[heap[r]] < A[heap[l]]) {
min_cand = r;
}
if (A[heap[min_cand]] < A[heap[ix]]) {
swap(min_cand, ix);
ix = min_cand;
l = 2 * ix;
r = 2 * ix+1;
} else {
break;
}
}
}
void heapify_up(int ix) {
int p = ix / 2;
while (ix >= 1 && p >= 1) {
if (A[heap[ix]] < A[heap[p]]) {
swap(ix, p);
ix = p;
p = ix / 2;
} else {
break;
}
}
}
void pop(int ix) {
int h_ix = pos[ix];
heap[h_ix] = heap[L];
pos[heap[L--]] = h_ix;
pos[ix] = 0;
//cout << "A: ";
//for (int i = 1; i <= contor; ++i) {
//cout << A[i] << " ";
//}
//cout << endl;
//cout << "h: ";
//for (int i = 1; i <= L; ++i) {
//cout << heap[i] << " ";
//}
//cout << endl;
//cout << "pos: ";
//for (int i = 1; i <= contor; ++i) {
//cout << pos[i] << " ";
//}
//cout << endl;
if (h_ix > 1 && A[heap[h_ix]] < A[heap[h_ix / 2]]) {
heapify_up(h_ix);
} else {
heapify_down(h_ix);
}
}
int main() {
freopen("heapuri.in", "r", stdin);
freopen("heapuri.out", "w", stdout);
scanf("%d", &N);
while (N--) {
int qt, q;
scanf("%d", &qt);
if (qt == 1 || qt == 2) {
if (qt == 1) {
scanf("%d", &A[++contor]);
heap[++L] = contor;
pos[contor] = L;
heapify_up(L);
} else if (qt == 2) {
//cout << "A: ";
//for (int i = 1; i <= contor; ++i) {
//cout << A[i] << " ";
//}
//cout << endl;
//cout << "h: ";
//for (int i = 1; i <= L; ++i) {
//cout << heap[i] << " ";
//}
//cout << endl;
//cout << "pos: ";
//for (int i = 1; i <= contor; ++i) {
//cout << pos[i] << " ";
//}
//cout << endl;
scanf("%d", &q);
pop(q);
}
} else {
printf("%d\n", A[heap[1]]);
}
}
return 0;
}