Cod sursa(job #2545656)

Utilizator RedPipperNastasa Stefan-Alexandru RedPipper Data 13 februarie 2020 12:58:39
Problema Heapuri Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 kb
#include <bits/stdc++.h>
#define MAX (int)(2e5+1)
using namespace std;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");



int heap[MAX], siz, hist[MAX], nr;

void heapify(int poz)
{
    int parent = poz / 2;
    if(heap[parent]>=heap[poz] && parent!=poz)
    {
        swap(heap[parent], heap[poz]);
        heapify(parent);
    }

}

void ballance()
{


}

void addElem(int a)
{
    hist[++nr] = a;
    heap[siz] = a;

    heapify(siz);
    ++siz;
}

void dell(int poz)
{
    int left = poz*2+1;
    int right = poz*2+2;
    int td = -1;
    
    if(left < siz && right < siz && heap[left]<=heap[right])
        td = left;
    else if(left < siz && right < siz && heap[left]>heap[right])
        td = right;
    else if(left<siz)
        td=left;
    else if (right<siz)
        td=right;
    if(td!=-1)
    {
        swap(heap[poz], heap[td]);
        dell(td);
    }
    
}

void rmElem(int poz)
{
    int nod = hist[poz];
    int toDel = 0;
    for(int i = 0;i<=siz;++i)
    {
        if(nod == heap[i])
        {
            toDel = i;
            break;
        }
    }

    dell(toDel);
    heap[siz]=0;
    --siz;


}

int main()
{
    int n;
    fin>>n;;
    while(n--)
    {
        int x;
        int op;
        fin>>op;
        switch(op)
        {
            case 1:
                fin>>x;
                addElem(x);
                break;
            case 2:
                fin>>x;
                rmElem(x);
                break;
            case 3:
                fout<<heap[0]<<endl;
                break;
        }
    }


    return 0;
}