Cod sursa(job #2206525)

Utilizator Raoul_16Raoul Bocancea Raoul_16 Data 22 mai 2018 20:27:41
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.84 kb
#include <bits/stdc++.h>
using namespace std;
const int MAX = 200005;
int N, quest, node, nh;
int values[MAX], heap[MAX], pos[MAX];
bool comp(int, int);
void swapX(int, int);
void upHeap(int);
void downHeap(int);
void addNode(int);
void delNode(int);
void solve();
int main(){
    solve();
    return 0;
}
bool comp(int x, int y){
    return values[x] < values[y];
}
void swapX(int child, int parent){
    swap(heap[child], heap[parent]);
    swap(pos[heap[child]], pos[heap[parent]]);
}
void upHeap(int child){
    int parent = child >> 1;     //divided by 2, only that it's divided binary
    bool var = comp(heap[child], heap[parent]); // Min Heap property(child's value is less than father's value)
    if(parent and var){
        swapX(child,parent);     //swap the position and the value itself
        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);
    heap[nh--] = 0;
    pos[heap[nh]] = 0;
    downHeap(node);
}
void solve(){
    ifstream f("heapuri.in");
    ofstream g("heapuri.out");
    f >> N;
    for(int i = 0; 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"; //value of the root, in fact
        }
    }
}