Cod sursa(job #2894577)

Utilizator RaduAntoneoAntonio Alexandru Radu RaduAntoneo Data 27 aprilie 2022 23:22:25
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.63 kb
#pragma GCC optimize("O3")
#include <bits/stdc++.h>
using namespace std;

int poz_curr = 0;
int heap[200001];
int pozitii[200001];

void urca(int poz) {
    while(poz) {
        int tata = (poz - 1) / 2;
        if(heap[tata] > heap[poz]) {
            swap(heap[tata], heap[poz]);
            poz = tata;
        }
        else break;
    }
}

void adauga(int x) {
    heap[poz_curr++] = x;
    urca(poz_curr - 1);
}

void coboara(int poz) {
    int st = poz * 2 + 1;
    int dr = st + 1;
    if(st >= poz_curr)
        return;
    if(heap[st] < heap[dr]) {
        if(heap[st] < heap[poz]) {
            swap(heap[poz], heap[st]);
            coboara(st);
        }
    } 
    else if(heap[dr] < heap[poz]) {
        swap(heap[poz], heap[dr]);
        coboara(dr);
        }
    return;
}

void sterge(int poz) {
    if(poz_curr == 0)
        return;
    heap[poz] = heap[poz_curr - 1];
    poz_curr--;
    urca(poz);
    coboara(poz);
}

ifstream f("heapuri.in");
ofstream g("heapuri.out");
#define cin f
#define cout g

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    int t, op, nr, cnt = 1;
    cin >> t;
    for(int k = 0; k < t; k++) {
        cin >> op;
        if(op == 3) cout << heap[0] << '\n';
        else {
            cin >> nr;
            if(op == 1) {adauga(nr); pozitii[cnt++] = nr;}
            else {
                for(int i = 0; i < poz_curr; i++) {
                    if(pozitii[nr] == heap[i]) {
                        sterge(i);
                        break;
                    }
                }

            }
        }  
    }
}