Cod sursa(job #1207267)

Utilizator RathebaSerbanescu Andrei Victor Ratheba Data 12 iulie 2014 17:40:41
Problema Heapuri Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.61 kb
#include <cstdio>
#include <vector>

using namespace std;
#define MAX 200005
#define INF 1000000005

vector<int> v;
vector<int> heap;

int vpoz[MAX];
void add(int val, int poz);
void del(int poz);
void goup(int poz);
void godown(int nod);
int n;
int main()
{
    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);
    int cod, x, i;
    v.push_back(0); heap.push_back(0);
    scanf("%d",&n);
    for(i=1; i<=n; i++)
    {
        scanf("%d",&cod);
        if(cod==3)
            printf("%d\n",v[heap[1]]);
        else
        {
            scanf("%d",&x);
            if(cod==1){
                v.push_back(x);
                add(x, v.size()-1);
            }
            else{
                del(x);
            }
        }
    }
    return 0;
}
void add(int val, int poz)
{
    heap.push_back(poz);
    vpoz[v.size()-1] = heap.size()-1;
    goup(heap.size()-1);
}
void goup(int poz)
{
    int aux;
    if(v[heap[poz]] < v[heap[poz/2]])
    {
        aux=heap[poz]; heap[poz]=heap[poz/2]; heap[poz/2]=aux;
        aux=vpoz[heap[poz]]; vpoz[heap[poz]]=vpoz[heap[poz/2]]; vpoz[heap[poz/2]]=aux;
        goup(poz/2);
    }
 }
void del(int poz)
{
    v[heap[vpoz[poz]]] = INF;
    godown(vpoz[poz]);
}
void godown(int nod)
{
    int nextnod, aux;
    if(nod*2 > heap.size()-1)
        return;
    nextnod = nod*2 + (v[heap[nod*2]] > v[heap[nod*2+1]] and nod*2+1<=heap.size()-1);
    aux=heap[nod]; heap[nod]=heap[nextnod]; heap[nextnod]=aux;
    aux=vpoz[heap[nod]]; vpoz[heap[nod]]=vpoz[heap[nextnod]]; vpoz[heap[nextnod]]=aux;
    godown(nextnod);
}