Cod sursa(job #2206563)

Utilizator Raoul_16Raoul Bocancea Raoul_16 Data 22 mai 2018 22:50:01
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 2.21 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();
    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";
        }
    }
    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 and comp(heap[child], heap[parent])){
        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);
    child += (child + 1 <= nh and comp(heap[child + 1], heap[child]));
    //bool var3 = comp(heap[child], heap[parent]);
    if(child <= nh and comp(heap[child], heap[parent])){
        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);
}
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";
        }
    }
}