Cod sursa(job #2137741)

Utilizator TudorVersoiuVersoiu Tudor Sorin TudorVersoiu Data 21 februarie 2018 00:14:47
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.79 kb
#include <iostream>
#include <fstream>


using namespace std;
ifstream f("heapuri.in" );
ofstream g("heapuri.out");

int N, hSize, nChron;
struct helem
{
    int v;
    int nr;
} heap[200005];;
int poz[200005];

void hswap(int x, int y) {
    swap(    heap[x].v  ,     heap[y].v  );
    swap(poz[heap[x].nr], poz[heap[y].nr]);
    swap(    heap[x].nr ,     heap[y].nr );
}

void realocare(int x) {
    int parent = x/2;

    if ( parent < 0 ) return;

    if ( heap[parent].v > heap[x].v ) {
        hswap(parent, x);
        realocare(parent);
    }
}

void InsertNode(int x) {
    ++hSize;
    heap[hSize].v  = x;
    heap[hSize].nr = ++nChron;

    poz[nChron] = hSize;
    realocare(hSize);
}

void Shift(int x) {
    int child1 = 2*x;
    int child2 = 2*x+1;
    int minchild = child1;

    if ( child1 > hSize )
    {
        hswap(x, hSize);
        return;
    }

    if ( heap[child2].v < heap[minchild].v )
        minchild = child2;

    if ( child1 == hSize ) minchild = child1;
    hswap(minchild, x);
    Shift(minchild);
}

void DeleteNode(int x) {
    Shift(x);
    --hSize;
}

int bCount(int x)
{
    int result = 0;
    while ( x )
    {
        result += x&1;
        x >>= 1;
    }
    return result;
}
void AfisareHeap()
{
    for ( int i=1; i<=hSize; i++ )
    {
        if ( bCount(i) == 1 ) cout << '\n';
        cout << heap[i].v;
    }
}

int main() {
    f >> N;

    int op, x;
    for ( int i=1; i<=N; i++ ) {
        f >> op;

        if ( op == 1 ) {
            f >> x;
            InsertNode(x);
        }
        if ( op == 2 ) {
            f >> x;
            DeleteNode(poz[x]);
        }
        if ( op == 3 )
            if ( hSize > 0 )
                g << heap[1].v << '\n';
    }
}