Cod sursa(job #1309246)

Utilizator somuBanil Ardej somu Data 5 ianuarie 2015 16:36:31
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.78 kb
#include <iostream>
#include <fstream>
#define nmax 200005

using namespace std;

int N;
int op, x, sizeOfHeap;
int POZ[nmax], HEAP[nmax], V[nmax];

void updateUp(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]);
        updateUp(nod/2);
    }
}

void updateDown(int nod) {
    
    int fiuMin = nod;
    int st = 2 * nod;
    int dr = 2 * nod + 1;
    
    if (st <= sizeOfHeap && V[ HEAP[ fiuMin ] ] > V[ HEAP[st] ] ) fiuMin = st;
    if (dr <= sizeOfHeap && V[ HEAP[ fiuMin ] ] > V[ HEAP[dr] ] ) fiuMin = dr;
    
    if (fiuMin == nod) return;
    
    swap(POZ[ HEAP[nod] ], POZ[ HEAP[fiuMin] ]);
    swap(HEAP[nod], HEAP[fiuMin]);
    
    updateDown(fiuMin);
    
}

void adauga(int x) {
    sizeOfHeap++;
    V[0]++;
    V[ V[0] ] = x;
    POZ[ V[0] ] = sizeOfHeap;
    HEAP[ sizeOfHeap ] = V[0];
    updateUp(sizeOfHeap);
}

void sterge(int nod) {
    
    int poz = POZ[nod];
    
    swap(POZ[ HEAP[poz] ], POZ[ HEAP[sizeOfHeap] ]);
    swap(HEAP[poz], HEAP[sizeOfHeap]);
    
    sizeOfHeap--;
    
    if (poz != 1 && V[ HEAP[poz] ] < V[ HEAP[poz/2] ])
        updateUp(poz);
    else
        updateDown(poz);
    
}

int main() {
    
    ifstream fin("heapuri.in");
    ofstream fout("heapuri.out");
    
    fin >> N;
    
    for (int i = 1; i <= N; i++) {
        fin >> op;
        
        switch (op) {
            case 1:
                fin >> x;
                adauga(x);
                break;
            case 2:
                fin >> x;
                sterge(x);
                break;
            case 3:
                fout << V[ HEAP[1] ] << "\n";
                break;
        }
        
    }
    
    fin.close();
    fout.close();
    
    return 0;
}