Pagini recente » Cod sursa (job #2135323) | Cod sursa (job #1907097) | Cod sursa (job #2519717) | Cod sursa (job #1117258) | Cod sursa (job #3260300)
#include <iostream>
#define MAX_N 200005
using namespace std;
int heap[MAX_N];
int all;
int v[MAX_N];
int orig[MAX_N];
int n;
void swapAll(int a, int b)
{
swap(orig[a], orig[b]);
swap(heap[a], heap[b]);
v[orig[a]] = a;
v[orig[b]] = b;
}
void goDown(int pos)
{
while (true) {
int child1 = pos * 2 + 1;
int child2 = pos * 2 + 2;
int val1 = (child1 >= n) ? 1000000005 : heap[child1];
int val2 = (child2 >= n) ? 1000000005 : heap[child2];
if (val1 <= val2 && val1 < heap[pos]) {
swapAll(pos, child1);
pos = child1;
} else if (val2 <= val1 && val2 < heap[pos]) {
swapAll(pos, child2);
pos = child2;
} else {
break;
}
}
}
void goUp(int pos)
{
while (pos != 0) {
int parent = (pos - 1) / 2;
if (heap[parent] > heap[pos]) {
swapAll(parent, pos);
pos = parent;
} else {
break;
}
}
}
void add(int a)
{
heap[n] = a;
orig[n] = all;
v[all] = n;
int pos = n;
n++;
all++;
goUp(pos);
}
void remove(int posInHeap)
{
n--;
swapAll(n, posInHeap);
goDown(posInHeap);
}
int main()
{
FILE *fin = fopen("heapuri.in", "r");
FILE *fout = fopen("heapuri.out", "w");
int q;
fscanf(fin, "%d\n", &q);
while (q--) {
int t, x;
fscanf(fin, "%d", &t);
if (t == 1 || t == 2)
fscanf(fin, "%d", &x);
if (t == 1) {
add(x);
} else if (t == 2) {
remove(v[x - 1]);
} else {
fprintf(fout, "%d\r\n", heap[0]);
}
}
}