Cod sursa(job #1974528)

Utilizator RathebaSerbanescu Andrei Victor Ratheba Data 27 aprilie 2017 22:26:32
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 2.36 kb
#include <fstream>

using namespace std;

ifstream fin ("heapuri.in");
ofstream fout ("heapuri.out");

#define MAX 200002

int heap[MAX];
int vpoz[MAX];
int values[MAX];


int lastElem, n;

void afisHeap();
void insertHeap(int elem);
void deleteHeap(int poz);
void rebuildHeapInsert();
void rebuildHeapDelete(int poz);
void swapHeap(int poz1, int poz2);
void goUp(int node);



int main()
{
    int command, elem, poz;

    int ii = 0;
    lastElem = 1;

    fin >> n;
    for (int i = 1; i <= n; i++) {
        fin >> command;

        if (command == 1) {
            fin >> elem;
            values[++ii] = elem;

            insertHeap(ii);

        } else if (command == 2) {
            fin >> poz;
            deleteHeap(vpoz[poz]);

        } else {
            afisHeap();
        }
    }
    return 0;
}
void afisHeap()
{
    fout << values[heap[1]] << '\n';
}
void insertHeap(int pos)
{
    heap[lastElem] = pos;
    vpoz[pos] = lastElem;

    lastElem++;
    rebuildHeapInsert();
}
void deleteHeap(int poz)
{
    //heap[poz] = heap[lastElem - 1];
    swapHeap(poz, lastElem - 1);

    lastElem--;
    rebuildHeapDelete(poz);
}

void goUp(int node)
{
    int father = node / 2;
    if(values[heap[node]] < values[heap[father]]) {
        swapHeap(father, node);
        goUp(father);
    }
}

void rebuildHeapInsert()
{
    int father;
    int child = lastElem - 1;
    father = child / 2;
    while(values[heap[father]] > values[heap[child]]) {
        swapHeap(father, child);

        child = father;
        father = child / 2;
    }
}
void swapHeap(int poz1, int poz2)
{
    int aux = heap[poz1];
    heap[poz1] = heap[poz2];
    heap[poz2] = aux;

    vpoz[heap[poz1]] = poz1;
    vpoz[heap[poz2]] = poz2;
}
void rebuildHeapDelete(int poz)
{
    int child1, child2, smallestChild;

    child1 = poz * 2;
    child2 = child1 + 1;

    if(child1 >= lastElem) {
        //no children
        return;
    } else if(child2 >= lastElem) {
        //only-child
        smallestChild = child1;
    }

    if(heap[child1] < heap[child2]) {
        smallestChild = child1;
    } else {
        smallestChild = child2;
    }

    if(values[heap[smallestChild]] >= values[heap[poz]]) {
        return;
    }

    swapHeap(smallestChild, poz);
    rebuildHeapDelete(smallestChild);
}