Cod sursa(job #1169495)

Utilizator CosminRusuCosmin Rusu CosminRusu Data 11 aprilie 2014 15:26:40
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.48 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <bitset>
#include <string.h>
#include <algorithm>
#include <iomanip>
#include <math.h>
#include <time.h>
#include <stdlib.h>
#include <set>
#include <map>
#include <string>
#include <queue>
#include <deque>

using namespace std;

const char infile[] = "heapuri.in";
const char outfile[] = "heapuri.out";

ifstream fin(infile);
ofstream fout(outfile);

const int MAXN = 200005;
const int oo = 0x3f3f3f3f;

typedef vector<int> Graph[MAXN];
typedef vector<int> :: iterator It;

const inline int min(const int &a, const int &b) { if( a > b ) return b;   return a; }
const inline int max(const int &a, const int &b) { if( a < b ) return b;   return a; }
const inline void Get_min(int &a, const int b)    { if( a > b ) a = b; }
const inline void Get_max(int &a, const int b)    { if( a < b ) a = b; }

int M, v;
int Heap[MAXN], Pos[MAXN], V[MAXN], P;
int N;

inline int Father(int x) {
    return x >> 1;
}

inline int leftSon(int x) {
    return x << 1;
}

inline int rightSon(int x) {
    return (x << 1) | 1;
}

inline void Percolate(int K) {
    /// go from father to father and check the heap preoperty
    while(K > 1 && V[ Heap[K] ] < V[ Heap[Father(K)] ]) {
        swap(Heap[K], Heap[Father(K)]);
        //ap(P[Heap[K]], P[Heap[Father(K)]]);
        Pos[ Heap[K]] = K;
        Pos[ Heap[Father(K)] ] = Father(K);
        K = Father(K);
    }
}

inline void Sift(int K) {
    int son = 0;
    do {
        son = 0;
        if(leftSon(K) <= N) {
            son = leftSon(K);
            if(rightSon(K) <= N && V[ Heap[rightSon(K)] ] < V[ Heap[son] ])
                son = rightSon(K);
            if(V[ Heap[son] ] >= V[ Heap[K] ])
                son = 0;
        }
        if(son) {
            swap(Heap[son], Heap[K]);
            Pos[ Heap[son] ] = son;
            Pos[ Heap[K] ] = K;
            K = son;
        }
    } while(son);
}

inline void Insert(int x) {
    V[++ v] = x;
    Heap[++ N] = v;
    Pos[v] = N;
    Percolate(N);
}

inline void Erase(int K) {
    Heap[Pos[K]] = Heap[N];
    -- N;
    Percolate(Pos[K]);
    Sift(Pos[K]);
}

inline int Query() {
    return V[Heap[1]];
}

int main() {
    fin >> M;
    for(int i = 1 ; i <= M ; ++ i) {
        int op, x;
        fin >> op;
        if(op == 1) {
            fin >> x;
            Insert(x);
        }
        if(op == 2) {
            fin >> x;
            Erase(x);
        }
        if(op == 3)
            fout << Query() << '\n';
    }
    fin.close();
    fout.close();
    return 0;
}