Cod sursa(job #3305938)

Utilizator InformaticianInDevenire1Munteanu Mihnea Gabriel InformaticianInDevenire1 Data 6 august 2025 09:31:24
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.69 kb
#include <bits/stdc++.h>

using namespace std;

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

struct Node{
    int val;
    int ind;
}heap[200005];

int xPos[200010];

int Father(int x){
    return x/2;
}

int LSon(int x){
    return x*2;
}

int RSon(int x){
    return x*2+1;
}

void SWAP(int n1,int n2){
    swap(heap[n1],heap[n2]);
    swap(xPos[heap[n1].ind], xPos[heap[n2].ind]);
}

void TopC(int pos){
    while(pos>1 and heap[pos].val<heap[Father(pos)].val){
        SWAP(pos,Father(pos));
        pos = Father(pos);
    }
}

void BottomC(int pos,int &Hsize){
    int son = -1;
    if (LSon(pos)<=Hsize){
        son = LSon(pos);
        if (RSon(pos)<=Hsize and heap[RSon(pos)].val<heap[LSon(pos)].val){
            son = RSon(pos);
        }
    }
    if (son==-1) return;
    if (heap[son].val<heap[pos].val){
        SWAP(son,pos);
        BottomC(son,Hsize);
    }
}

void Insert_Elem(int xval,int init_pos,int &Hsize){
    Hsize++;
    heap[Hsize].val = xval;
    heap[Hsize].ind = init_pos;
    xPos[heap[Hsize].ind] = Hsize;
    TopC(Hsize);
}

void Delete_Elem(int ind,int &Hsize){
    int cPos = xPos[ind];
    SWAP(cPos,Hsize);
    Hsize--;
    TopC(cPos);
    BottomC(cPos,Hsize);
}

int main()
{
    int n,Hsize = 0,ins = 0;
    fin >> n;
    for (int i=1;i<=n;++i){
        int C;
        fin >> C;
        if (C==1){
            int x;
            fin >> x;
            ins++;
            Insert_Elem(x,ins,Hsize);
        }else if (C==2){
            int x;
            fin >> x;
            Delete_Elem(x,Hsize);
        }else{
            fout << heap[1].val << '\n';
        }
    }
    return 0;
}