Cod sursa(job #790156)

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

#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;

struct Heap {
    vector<int> heap;
    vector<int> value;
    vector<int> heap_pos;

    Heap()
    {
        heap.push_back(0);
        value.push_back(0);
        heap_pos.push_back(0);
    }

    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) < heap.size()) {
            int next = -1;
            if (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 min() {
        return value[heap[1]];
    }
};

int main(void) {
    Heap h;

    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;
            h.insert(x);
        } else if (op == DEL) {
            int x;
            fin >> x;
            h.remove(x);
        } else if (op == MIN) {
            fout << h.min() << endl;
        }
    }
    return 0;
}