Cod sursa(job #3171658)

Utilizator adelachiritaAdela Chirita adelachirita Data 19 noiembrie 2023 12:13:57
Problema Heapuri Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.61 kb
#include <bits/stdc++.h>
#define NM 200005

using namespace std;

ifstream fin("heapuri.in");
ofstream fout("heapuri.out");

int n;

int l, p[NM];

struct nod
{
    int val, pos;
}h[NM];

void promoveaza(int i)
{
    while(i != 1 and h[i].val < h[i / 2].val){
        swap(p[h[i].pos], p[h[i / 2].pos]);
        swap(h[i], h[i / 2]);
        i /= 2;
    }
}

void inserteaza(int x, int pos)
{
    l++;
    h[l].val = x;
    h[l].pos = pos;
    p[pos] = l;

    int i = l;
    promoveaza(i);
}

void sterge(int pos)
{
    swap(p[h[pos].pos], p[h[l].pos]);
    swap(h[pos], h[l]);
    l--;

    if(pos > 1 and h[pos / 2].val > h[pos].val){
        promoveaza(pos);
    }
    else{
        while((pos * 2 <= l and h[pos * 2].val < h[pos].val) or
              (pos * 2 + 1 <= l and h[pos * 2 + 1].val < h[pos].val)){
            if(pos * 2 + 1 > l or h[pos * 2].val < h[pos * 2 + 1].val){
                swap(p[h[pos].pos], p[h[pos * 2].pos]);
                swap(h[pos].val, h[pos * 2].val);
            }
            else{
                swap(p[h[pos].pos], p[h[pos * 2 + 1].pos]);
                swap(h[pos].val, h[pos * 2 + 1].val);
            }
        }
    }
}

int main()
{
    fin >> n;
    int nr = 0;
    for(int i = 1; i <= n; i++){
        int x, t;
        fin >> t;
        if(t == 1){
            fin >> x;
            nr++;
            inserteaza(x, nr);
        }
        else if(t == 2){
            fin >> x;
            sterge(p[x]);
        }
        else if(t == 3){
            fout << h[1].val << '\n';
        }
    }

    return 0;
}