Cod sursa(job #3126502)

Utilizator Botnaru_VictorBotnaru Victor Botnaru_Victor Data 6 mai 2023 18:09:08
Problema Heapuri Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.63 kb
#include <bits/stdc++.h>

using namespace std;

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


const int MN = 10001;
const int INF = 0x3f3f3f3f;

//valorile numerelor (in ordine cronologica)
int v[MN];

//minheap - indexurile numerelor, aranjate sub forma de heap  (v[h[x]]<v[h[x*2]])
// tine minte o pozitie din v
int h[MN], hk;

//poz[i] = unde in heap se afla elementul cu indexul i
//tine minte o pozitie din h
int poz[MN];



//x este o pozitie in heap
void upheap(int x)
{
    if( v[h[x]] < v[h[x/2]])
    {
        swap(h[x], h[x/2]);

        poz[h[x]] = x;
        poz[h[x/2]] = x/2;

        upheap(x/2);

    }
}

void downheap(int x)
{
    if(x*2>hk) return;
    int minCopil = x*2;

    if(x*2+1<=hk && v[h[minCopil]] > v[h[x*2+1]]) minCopil= x*2+1;

    if( v[h[x]] > v[h[minCopil]])
    {
        swap( h[x], h[minCopil]);

        poz[h[x]] = x;
        poz[h[minCopil]] = minCopil;

        downheap(minCopil);
    }
}

//x este o pozitie din v
void deleteElement(int x)
{
    swap( h[poz[x]], h[hk]);

    poz[h[poz[x]]] = poz[x];

    hk--;

    downheap(poz[x]);

}

void addElement(int val)
{
    hk++;
    v[hk] = val;

    h[hk] = hk;
    poz[hk] = hk;

    upheap(hk);
}


int main()
{
    int n;
    int q,a;

    f>>n;

    for(int i=1;i<=n;i++)
    {
        f>>q;
        if(q==1)
        {
            f>>a;
            addElement(a);
        }
        if(q==2)
        {
            f>>a;
            deleteElement(a);
        }
        if(q==3)
        {
            g<<v[h[1]]<<'\n';
        }
    }

    return 0;
}