Pagini recente » Cod sursa (job #2062967) | Cod sursa (job #714653) | Cod sursa (job #1995220) | ONIS 2016, Clasament Runda 1 | Cod sursa (job #1000561)
#include <iostream>
#include <fstream>
using namespace std;
int heap[200001];
int poz[200001];
int ph[200001];
int lenght = 0;
int last = 0;
int pow(int x) {
int y = 1;
while(x-->0) y*=2;
return y;
}
int lc(int x) {
return x*2;
}
int rc(int x) {
return x*2+1;
}
int parent(int x) {
return x/2;
}
void swap(int p, int x) {
int aux = heap[p];
heap[p] = heap[x];
heap[x] = aux;
aux = poz[ph[p]];
poz[ph[p]] = poz[ph[x]];
poz[ph[x]] = aux;
aux = ph[p];
ph[p] = ph[x];
ph[x] = aux;
}
void verify(int x) {
int h=0; // nivelul in heap
while(pow(h+1)<x) h++;
int p = parent(x);
if(heap[p]>heap[x]) {
swap(p,x);
verify(p);
}
}
void down(int x) {
if(x>lenght) return;
if(lc(x)<rc(x)) {
swap(lc(x),x);
down(lc(x));
} else {
swap(rc(x),x);
down(rc(x));
}
}
void insert(int x) {
heap[++lenght] = x;
poz[++last] = lenght;
ph[lenght] = last;
verify(lenght);
}
void pop(int x) {
heap[poz[x]] = heap[lenght--];
poz[x] = lenght--;
verify(x);
down(x);
}
int main() {
int n;
int o, p;
ifstream f("heapuri.in");
ofstream fout("heapuri.out");
f>>n;
while(n-->0) {
f>>o;
if(o==1) {f>>p;insert(p);}
if(o==2) {f>>p;pop(p);}
if(o==3) fout<<heap[1]<<endl;
}
return 0;
}