Cod sursa(job #2925352)

Utilizator mihaistamatescuMihai Stamatescu mihaistamatescu Data 14 octombrie 2022 22:41:49
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <fstream>
#include <iostream>

using namespace std;

int n, h[200010], poz[200010], pozpoz[200010];

void upHeap(int k){
    while (k>1&&h[k]<h[k/2]){
        swap(h[k], h[k/2]);
        swap(poz[pozpoz[k]], poz[pozpoz[k/2]]);
        swap(pozpoz[k], pozpoz[k/2]);
        k/=2;
    }
}
void downHeap(int k){
    while (2*k<=n){
        int fiu=2*k;
        if (fiu+1<=n&&h[fiu+1]>h[fiu]){
            fiu++;
        }
        if (h[k]>h[fiu]){
            swap(h[k], h[fiu]);
            swap(poz[pozpoz[k]], poz[pozpoz[fiu]]);
            swap(pozpoz[k], pozpoz[fiu]);
            k=fiu;
        }
    }
}
int q, tip, k, x;
int main() {
    ifstream fin("heapuri.in");
    ofstream fout("heapuri.out");
    fin>>q;
    while(q--){
        fin>>tip;
        if (tip==1){
            fin>>h[++n];
            poz[++k]=n;
            pozpoz[n]=k;
            upHeap(n);
        }
        if (tip==2){
            fin>>x;
            int p=poz[x];
            swap(h[p], h[n]);
            swap(poz[x], poz[pozpoz[n]]);
            swap(pozpoz[p], pozpoz[n]);
            n--;
            downHeap(p);
        }
        if (tip==3){
            fout<<h[1]<<"\n";
        }
    }
    return 0;
}