Cod sursa(job #3362395)

Utilizator RZV139fjDragomir Ioan Razvan RZV139fj Data 8 august 2026 12:08:57
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.19 kb
#include <bits/stdc++.h>

using namespace std;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
long long n,q;

struct{
    int val;
    int poz;

}heap[200005];

int pozitii[200005];


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


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

void jos(int x)
{
    int son;
    do
    {
        son=0;
        if(fiu_st(x)<=n)
        {
            son=fiu_st(x);
            if(fiu_dr(x)<=n and heap[fiu_dr(x)].val<heap[son].val)
            {
                son=fiu_dr(x);
            }
            if(heap[son].val>heap[x].val)
            {
                son=0;
            }

            if(son)
            {
                swap(heap[son],heap[x]);
                pozitii[heap[x].poz] = x;
                pozitii[heap[son].poz] = son;
                x=son;
            }
        }


    }while(son);
}

void sus(int x)
{
    int key=heap[x].val;
    int care=heap[x].poz;
    while(x>1 and heap[tata(x)].val>key)
    {
        heap[x].val=heap[tata(x)].val;
        heap[x].poz=heap[tata(x)].poz;
        pozitii[heap[x].poz]=x;
        x=tata(x);
    }

    heap[x].val=key;
    heap[x].poz=care;
    pozitii[care]=x;
}

void build()
{
    for(int i=n/2;i>=1;i--)
    {
        jos(i);
    }
}

void sterge(int x)
{
    heap[x].val=heap[n].val;
    heap[x].poz=heap[n].poz;
    pozitii[heap[x].poz]=x;
    n--;
    if(heap[x].val<heap[tata(x)].val and x>1)
    {
        sus(x);
    }
    else if(x<n)
    {
        jos(x);
    }
}

void add(int x, int care)
{
    heap[++n].val=x;
    heap[n].poz=care;
    pozitii[care]=n;
    if(heap[tata(n)].val>heap[n].val)
    {
        sus(n);
    }
}





int main()
{
    fin>>q;
    int cnt=0;
    for(int i=1;i<=q;i++)
    {
        int tip; int x;
        fin>>tip;
        if(tip==1)
        {
            cnt++;
            fin>>x;
            add(x,cnt);
        }else if(tip==2)
        {
            fin>>x;
            sterge(pozitii[x]);
        }else if(tip==3)
        {
            fout<<heap[1].val<<'\n';
        }
    }









    return 0;
}