Cod sursa(job #2262173)

Utilizator SqueekDanielTodasca Daniel SqueekDaniel Data 17 octombrie 2018 01:55:13
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.85 kb
#include <bits/stdc++.h>

#define Right 2*Index+1
#define Left  2*Index
#define MaxN  200005

std::ifstream InFile("heapuri.in");
std::ofstream OutFile("heapuri.out");

typedef void (*void_ptr)();
void_ptr Query[3];

int Q, NCitiri, Heap[MaxN], HeapSize;
int Poz[MaxN], Val[MaxN];

void Sift(int Index) {
    int Son = 1;

    while(Son) {
        if (Left <= HeapSize) {
            Son = Left;
            if(Right <= HeapSize && Val[Heap[Right]] < Val[Heap[Left]])
                Son = Right;

            if (Val[Heap[Son]] < Val[Heap[Index]]) {
                std::swap (Heap[Son], Heap[Index]);

                Poz[Heap[Son]] = Son;
                Poz[Heap[Index]] = Index;

                Index = Son;
            }
            else Son = 0;
        }
        else Son = 0;
    }
}

void Percolate(int Index = HeapSize) {
    while (Index>1 && Val[Heap[Index]] < Val[Heap[Index/2]]) {
        std::swap(Heap[Index], Heap[Index/2]);

        Poz[Heap[Index/2]] = Index/2;
        Poz[Heap[Index]] = Index;

        Index = Index/2;
    }
}

int x;
void Query1() {     // Update
    InFile >> x;

    Heap[++HeapSize] = ++NCitiri;
    Poz[NCitiri] = HeapSize;
    Val[NCitiri] = x;
    Percolate();
}
void Query2() {     // Cut
    InFile >> x;

    Heap[Poz[x]] = Heap[HeapSize--];
    Poz[Heap[Poz[x]]] = Poz[x];

    if (Poz[x] > 1 && (Val[Heap[Poz[x]/2]] > Val[Heap[Poz[x]]]))
        Percolate(Poz[x]);
    else
        Sift(Poz[x]);
}
void Query3() {     // Min
    OutFile << Val[Heap[1]] << '\n';
}
void Citire() {
    InFile >> Q;
}

void Rezolvare() {
    Query[0] = &Query1;
    Query[1] = &Query2;
    Query[2] = &Query3;

    int Type;
    while (Q--) {
        InFile >> Type;
        Query[Type-1]();
    }
}

int main()
{
    Citire();
    Rezolvare();

    return 0;
}