Cod sursa(job #2219263)

Utilizator Raoul_16Raoul Bocancea Raoul_16 Data 8 iulie 2018 10:42:56
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.7 kb
#include <fstream>
using namespace std;
const int MAX = 200005;
int N, quest, node, nh, 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;
    bool var = comp(heap[child], heap[parent]);
    if((parent > 0) 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){
    ++nh;
    heap[nh] = node;
    pos[node] = nh;
    upHeap(pos[node]); //here
}
void delNode(int node){
    swapX(node, nh);
    pos[heap[nh]] = 0;
    heap[nh] = 0;
    nh--;
    downHeap(node); //..and here
}
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:
            ++node;
            f >> values[node];
            addNode(node);
            break;
        case 2:
            f >> quest;
            delNode(pos[quest]);
            break;
        case 3:
            g << values[heap[1]] << "\n";
        }
    }
}