Cod sursa(job #2226559)

Utilizator Raoul_16Raoul Bocancea Raoul_16 Data 30 iulie 2018 12:42:34
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.6 kb
#include <fstream>
const int MAX = 2e5;
int N, quest, node, nh, values[MAX + 5], heap[MAX + 5], pos[MAX + 5];
bool comp(int, int);
void swapX(int, int);
void upHeap(int);
void downHeap(int);
void addNode(int);
void delNode(int);
int main(){
    std::ifstream f("heapuri.in");
    std::ofstream g("heapuri.out");
    f >> N;
    for(int i = 1; i <= N; ++i){
        f >> quest;
        switch(quest){
        case 1:
            f >> values[++node];
            addNode(node);
            break;
        case 2:
            f >> quest;
            delNode(pos[quest]);
            break;
        case 3:
            g << values[heap[1]] << "\n";
        }
    }
    return 0;
}
bool comp(int x, int y){
    return values[x] < values[y];
}
void swapX(int child, int parent){
    std::swap(heap[child], heap[parent]);
    std::swap(pos[heap[child]], pos[heap[parent]]);
}
void upHeap(int child){
    int parent = child >> 1;
    bool var = comp(heap[child], heap[parent]);
    if(parent and var){
        swapX(child,parent);
        upHeap(parent);
    }
}
void downHeap(int parent){
    int child = parent << 1;
    bool var = comp(heap[child + 1], heap[child]);
    bool var2 = child + 1 <= nh;
    child = child + (var and var2);
    bool var3 = comp(heap[child], heap[parent]);
    if(child <= nh and var3){
        swapX(parent, child);
        downHeap(child);
    }
}
void addNode(int node){
    heap[++nh] = node;
    pos[node] = nh;
    upHeap(pos[node]);
}
void delNode(int node){
    swapX(node, nh);
    pos[heap[nh]] = 0;
    heap[nh--] = 0;
    downHeap(node);
}