Cod sursa(job #790179)

Utilizator mihai0110Bivol Mihai mihai0110 Data 20 septembrie 2012 16:49:20
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 2.11 kb
#include <vector>
#include <fstream>
#include <iostream>

#define INS 1
#define DEL 2
#define MIN 3

#define LEFT(x) ((x) << 1)
#define RIGT(x) (((x) << 1) + 1)
#define PARENT(x) ((x) >> 1)

using namespace std;

vector<int> heap;
vector<int> value;
vector<int> heap_pos;

void swap(int &x, int &y) {
    int aux = x;
    x = y;
    y = aux;
}

void insert(int x)
{
    heap_pos.push_back(heap.size());
    heap.push_back(value.size());
    value.push_back(x);

    int node = heap.size() - 1;
    while (node != 1) {
        if (value[heap[node]] < value[heap[PARENT(node)]]) {
            int key = heap[node];
            int pkey = heap[PARENT(node)];
            swap(heap[node], heap[PARENT(node)]);
            heap_pos[key] = PARENT(node);
            heap_pos[pkey] = node;
            node = PARENT(node);
        } else {
            break;
        }
    }
}

void remove(int x)
{
    swap(heap[heap_pos[x]], heap[heap.size() - 1]);
    heap.pop_back();

    int node = heap_pos[x];
    heap_pos[heap[node]] = node;

    while (LEFT(node) < (int)heap.size()) {
        int next = -1;
        if ((int)heap.size() - 1 == LEFT(node)) {
            next = LEFT(node);
        } else {
            if (value[heap[LEFT(node)]] < value[heap[RIGT(node)]]) {
                next = LEFT(node);
            } else {
                next = RIGT(node);
            }
        }

        if (value[heap[node]] > value[heap[next]]) {
            heap_pos[heap[node]] = next;
            heap_pos[heap[next]] = node;
            swap(heap[node], heap[next]);
        } else {
            break;
        }

        node = next;
    }
}

int main(void) {
    heap.push_back(0);
    value.push_back(0);
    heap_pos.push_back(0);

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

    int n;
    fin >> n;
    while (n--) {
        int op;
        fin >> op;
        if (op == INS) {
            int x;
            fin >> x;
            insert(x);
        } else if (op == DEL) {
            int x;
            fin >> x;
            remove(x);
        } else if (op == MIN) {
            fout << value[heap[1]] << endl;
        }
    }
    return 0;
}