Cod sursa(job #1248292)

Utilizator gabrieligabrieli gabrieli Data 24 octombrie 2014 21:18:51
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.93 kb
#include <algorithm>
#include <cstdio>
#include <vector>

using namespace std;

typedef int heap_t;

struct Heap {
    vector<heap_t> data;
    vector<int> heap, pos_heap;
    
    int parent(int pos) { return (pos - 1) / 2; }
    int left_child(int pos) { return 2 * pos + 1; }
    int right_child(int pos) { return 2 * pos + 2; }
    
    void swaph(int i, int j) {
        swap(heap[i], heap[j]);
        pos_heap[heap[i]] = i;
        pos_heap[heap[j]] = j;
    }
    
    bool is_less(int i, int j) { return data[heap[i]] < data[heap[j]]; }
    
    void up(int i) {
        for (int p = parent(i); p != i && is_less(i, p); i = p, p = parent(p))
            swaph(i, p);
    }
    
    void down(int i) {
        int next;
        while (true) {
            if (left_child(i) < heap.size())
                next = left_child(i);
            else return;
            if (right_child(i) < heap.size() && is_less(right_child(i), next))
                next = right_child(i);
            
            if (! is_less(next, i)) return;
            
            swaph(i, next);
            i = next;
        }
    }
    
    void insert(int x) {
        data.push_back(x);
        heap.push_back(data.size() - 1);
        pos_heap.push_back(heap.size() - 1);
        
        up(heap.size() - 1);
    }
    
    void remove(int i) {
        i = pos_heap[i];
        swaph(i, heap.size() - 1);
        heap.pop_back();
        down(i);
    }
    
    int top() { return data[heap[0]]; }
} H;

int main() {
    freopen("heapuri.in", "r", stdin);
    freopen("heapuri.out", "w", stdout);
    
    int q, op, x, i;
    
    scanf("%d", &q);
    for (; q; --q) {
        scanf("%d", &op);
        if (op == 1) {
            scanf("%d", &x);
            H.insert(x);
        }
        else if (op == 2) {
            scanf("%d", &i);
            H.remove(i-1);
        }
        else
            printf("%d\n", H.top());
    }
    
    fclose(stdout);
    return 0;
    
    return 0;
}