Cod sursa(job #790087)

Utilizator sory1806Sandu Sorina-Gabriela sory1806 Data 20 septembrie 2012 12:56:32
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.87 kb

#include <iostream>
#include <fstream>
#include <vector>

#define OP_INSERT       1
#define OP_DELETE       2
#define OP_PRINT_MIN    3

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

std::vector<int> heap, track, elem;

void swap(int &a, int &b)
{
    int aux;

    aux = a;
    a = b;
    b = aux;
}

void heapInsert(int x)
{
    elem.push_back(x);
    heap.push_back(elem.size() - 1);
    track.push_back(heap.size() - 1);

    int i = heap.size() - 1;

    while (i / 2 > 0 && elem[heap[i]] < elem[heap[i / 2]]) {
        swap(heap[i], heap[i / 2]);
        track[heap[i]] = i;
        track[heap[i / 2]] = i / 2;
        i /= 2;
    }
}

void heapDelete(int pos)
{
    swap(heap[track[pos]], heap[heap.size() - 1]);
    heap.pop_back();

    int crt = track[pos];
    int nxt;

    track[heap[crt]] = crt;

    while ((int) heap.size() - 1 >= 2 * crt) {
        if ((int) heap.size() - 1 == 2 * crt) {
            nxt = 2 * crt;
        }
        else {
            if (elem[heap[2 * crt]] < elem[heap[2 * crt + 1]]) {
                nxt = 2 * crt;
            }
            else {
                nxt = 2 * crt + 1;
            }
        }

        if (elem[heap[crt]] > elem[heap[nxt]]) {
            swap(heap[crt], heap[nxt]);
            track[heap[crt]] = crt;
            track[heap[nxt]] = nxt;
        }
        else {
            break;
        }
        crt = nxt;
    }
}

int main()
{
    int noOp, op;

    f >> noOp;

    heap.push_back(0);
    track.push_back(0);
    elem.push_back(0);

    for (int i = 0; i < noOp; i ++) {
        f >> op;

        if (op == OP_INSERT) {
            int x;
            f >> x;
            heapInsert(x);
        }
        if (op == OP_DELETE) {
            int pos;
            f >> pos;
            heapDelete(pos);
        }
        if (op == OP_PRINT_MIN) {
            g << elem[heap[1]] << '\n';
        }
    }

    return 0;
}