Cod sursa(job #2845411)

Utilizator Theo14Ancuta Theodor Theo14 Data 7 februarie 2022 19:41:08
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.62 kb
#include<bits/stdc++.h>
using namespace std;

ifstream f("heapuri.in");
ofstream g("heapuri.out");

int heap[200002],n,n_heap,v[200002],k=0,poz[200002];

//v - valorile din heap
//heap - in heap tinem pozitile elementelor
//poz - poz[cv] este pozitia lui cv in heap

void add(int x)
{
    k++;
    v[k]=x;
    n_heap++;
    heap[n_heap]=k;
    poz[k]=n_heap;
    int current=n_heap;
    while(current>1 &&v[heap[current]]<v[heap[current/2]])
    {
        swap(heap[current],heap[current/2]);
        swap(poz[heap[current]],poz[heap[current/2]]);
        current/=2;
    }
}

void pop(int x)
{
    v[x]=-1;
    int current=poz[x];
    while(current>1 && v[heap[current]]<v[heap[current/2]])
    {
        swap(heap[current],heap[current/2]);
        swap(poz[heap[current]],poz[heap[current/2]]);
        current/=2;
    }
    heap[1]=heap[n_heap];
    poz[heap[1]]=1;
    n_heap--;
    int p=1;
    current=2;
    while(current<=n_heap)
    {
        if(current+1<=n_heap && v[heap[current+1]]<v[heap[current]])
            current=current+1;
        if(v[heap[current]]<v[heap[p]])
        {
            swap(heap[p],heap[current]);
            swap(poz[heap[current]],poz[heap[p]]);
        }
        p=current;
        current=2*p;
    }
}

int main()
{
    int i,ok,x;
    f>>n;
    for(i=1;i<=n;i++)
    {
        f>>ok;
        if(ok==1)
        {
            f>>x;
            add(x);
        }
        if(ok==2)
        {
            f>>x;
            pop(x);
        }
        if(ok==3)
        {
            g<<v[heap[1]]<<'\n';
        }
    }
    return 0;
}