Cod sursa(job #1210846)

Utilizator fromzerotoheroFROM ZERO fromzerotohero Data 21 iulie 2014 13:43:28
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.74 kb
#include <iostream>
#include <fstream>
#include <queue>
using namespace std;

#define nmax 200001
ifstream in("heapuri.in");
ofstream out("heapuri.out");

int n,i;
int tip,x,cntHeap;
int Heap[nmax],V[nmax],Poz[nmax];

void inSus(int nod) {
    
    if (nod == 1)
        return;
    
    if (V[ Heap[nod] ] < V[ Heap[nod/2] ])
        swap(Poz[ Heap[nod] ], Poz[ Heap[nod/2] ]),
        swap(Heap[nod], Heap[nod/2]),
        inSus(nod/2);
    
}

void inJos(int nod) {

    int fiuMin = nod;
    int st = nod*2;
    int dr = nod*2+1;
    
    if (st <= cntHeap && V[ Heap[st] ] < V[ Heap[fiuMin] ]) fiuMin = st;
    if (dr <= cntHeap && V[ Heap[dr] ] < V[ Heap[fiuMin] ]) fiuMin = dr;
    
    if (fiuMin == nod) return;
    
    swap(Poz[ Heap[nod] ], Poz[ Heap[fiuMin] ]);
    swap(Heap[nod], Heap[fiuMin]);
    
    inJos(fiuMin);
    
}

void adauga(int x) {

    ++cntHeap;
    ++V[0];
    V[ V[0] ] = x;
    
    Heap[ cntHeap ] = V[0];
    Poz[ V[0] ] = cntHeap;
    
    inSus(cntHeap);
    
}

void sterge(int x) {
    
    int poz_H = Poz[x]; // poz elementului care trebuie sters, in Heap
    
    Poz[ Heap[cntHeap] ] = Poz[ Heap[poz_H] ];
    
    Heap[ poz_H ] = Heap[ cntHeap ];
    
    --cntHeap;
    
    int nod = Poz[ Heap[poz_H] ];
    
    if (nod > 1 && V[ Heap[nod] ]  < V[ Heap[nod/2]]) {
        inSus(nod);
    } else inJos(nod);
    
}

int main() {

    in >> n;
    
    for (i=1; i<=n; i++) {
        
        in >> tip;
        
        if (tip == 1) {
            
            in >> x;
            adauga(x);
            
        } else if (tip == 2) {
            
            in >> x;
            sterge(x);
            
        } else {
            
            out << V[ Heap[1] ] << "\n";
            
        }
        
    }
    
    return 0;
}