Cod sursa(job #2691725)

Utilizator TheGodFather2131Alexandru Miclea TheGodFather2131 Data 29 decembrie 2020 18:40:45
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.92 kb
//ALEXANDRU MICLEA
 
#include <vector>
#include <algorithm>
#include <string>
#include <string.h>
#include <cstring>
#include <queue>
#include <map>
#include <set>
#include <unordered_map>
#include <time.h>
#include <iomanip>
#include <deque>
#include <math.h>
#include <cmath>
#include <assert.h>
#include <stack>
#include <bitset>
#include <random>
#include <chrono>
#include <assert.h>
 
using namespace std;
using ll = long long;
 
#include <fstream>
//ifstream cin("input.in"); ofstream cout("output.out");
ifstream cin("heapuri.in"); ofstream cout("heapuri.out");
 
//VARIABLES

const int maxn = 2e5 + 5;

int v[maxn], h[maxn], pos[maxn];
int n = 0, i = 0;

//FUNCTIONS

void upheap(int poz){

    while (poz / 2 && v[h[poz / 2]] > v[h[poz]]){
        swap(pos[h[poz / 2]], pos[h[poz]]);
        swap(h[poz/2] , h[poz]);
        poz /= 2;
    }
}

void downheap(int poz){
    int son;
    int ok = 1;
    while (ok && 2 * poz <= i){
        ok = 0;
        son = 2*poz;
        if (son <= i && v[h[son]] > v[h[son + 1]]){
            son++;
        }
        if (v[h[son]] < v[h[poz]]){
            swap (pos[h[son]], pos[h[poz]]);
            swap(h[son], h[poz]);
            poz = son;
            ok = 1;
        }
    }
}

void add(int val){
    n++, i++;
    v[n] = val;
    h[i] = n;
    pos[n] = i;
    upheap(i);

}

void remove(int poz){
    pos[h[i]] = poz;
    h[poz] = h[i];
    i--;

    if (poz / 2 && v[h[poz / 2]] > v[h[poz]]){
        upheap(poz);
    }
    else downheap(poz);

}

void query(){
    cout << v[h[1]] << '\n';
}

//MAIN
 
int main() {
    
    int n; cin >> n;
    for (int i = 1; i <= n; i++){
        int tip, val; cin >> tip;
        if (tip != 3){
            cin >> val;
        }

        if (tip == 1) add(val);
        if (tip == 2) remove(pos[val]);
        if (tip == 3) query();
    }
    
    return 0;
}