Pagini recente » Cod sursa (job #1909122) | Cod sursa (job #3265014) | Cod sursa (job #1840559) | Cod sursa (job #1125607) | Cod sursa (job #3260293)
#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 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]) {
swap(v[orig[pos]], v[orig[child1]]);
swap(orig[pos], orig[child1]);
swap(heap[pos], heap[child1]);
pos = child1;
} else if (val2 <= val1 && val2 < heap[pos]) {
swap(v[orig[pos]], v[orig[child2]]);
swap(orig[pos], orig[child2]);
swap(heap[pos], heap[child2]);
pos = child2;
} else {
break;
}
}
}
void goUp(int pos)
{
while (pos != 0) {
int parent = (pos - 1) / 2;
if (heap[parent] > heap[pos]) {
swap(v[orig[parent]], v[orig[pos]]);
swap(orig[parent], orig[pos]);
swap(heap[parent], heap[pos]);
pos = parent;
} else {
goDown(pos);
break;
}
}
}
void add(int a)
{
heap[n] = a;
orig[n] = all;
int pos = n;
v[all] = n;
n++;
goUp(pos);
all++;
}
void remove(int posInHeap)
{
n--;
swap(heap[n], heap[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]);
}
}
}