Cod sursa(job #1194727)

Utilizator mariusn01Marius Nicoli mariusn01 Data 4 iunie 2014 18:24:32
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.37 kb
#include <fstream>
#define DIM 200010
using namespace std;

int a[DIM];
int h[DIM];
int poz[DIM];

int n, t, c, p, dh, o, x, aux;

// n = numarul de inserturi facute
// dh = numarul curent de elemente din heap
int main() {
    ifstream fin("heapuri.in");
    ofstream fout("heapuri.out");
    fin>>t;
    for (;t--;) {
        fin>>o;
        if (o == 3) {
            fout<<a[h[1]]<<"\n";
        }
        if (o == 1) {
            // insert
            fin>>x;
            a[++n] = x;
            // pun indicele n in heap la final
            dh++;
            h[dh] = n;
            poz[n] = dh;
            //urc elementul in heap
            c = dh;
            p = c/2;
            while (p>0) {
                if ( a[ h[c] ] < a[ h[p] ] ) {
                    aux = h[c];
                    h[c] = h[p];
                    h[p] = aux;
                    poz[ h[c] ] = c;
                    poz[ h[p] ] = p;
                } else
                    break;

                c = p;
                p = p/2;

            }
        }
        if (o == 2) {
            fin>>x;
            //sterg din heap elementul aflat e pozitia x in a
            //el se va afla in heap pe pozitia poz[x]
            a[x] = -1;
            //elementul de pe poz poz[x] il voi urca dar el va ajunge pana in radacina
            c = poz[x];
            p = c/2;
            while (p!=0) {
                if ( a[ h[c] ] < a[ h[p] ] ) {
                    aux = h[c];
                    h[c] = h[p];
                    h[p] = aux;
                    poz[ h[c] ] = c;
                    poz[ h[p] ] = p;
                } else
                    break;

                c = p;
                p = p/2;
            }

            // sterg radacina
            h[1] = h[dh];
            poz[ h[1] ] = 1;
            dh--;
            p = 1;
            c = 2;
            while (c <= dh) {
                if (c + 1 <= dh && a[ h[c+1] ] < a[ h[c] ])
                    c++;
                if (a[  h[p] ] > a[ h[c] ]) {
                    aux = h[p];
                    h[p] = h[c];
                    h[c] = aux;
                    poz[ h[c] ] = c;
                    poz[ h[p] ] = p;
                } else
                    break;
                p = c;
                c = 2*p;
            }
        }
    }

    return 0;
}