Cod sursa(job #2605137)

Utilizator MerlinTheWizardMelvin Abibula MerlinTheWizard Data 24 aprilie 2020 14:56:38
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.75 kb
#include<iostream>
#include<fstream>
using namespace std;
ifstream f("heapuri.in");
ofstream g("heapuri.out");
int nr,v[200001];
struct he
{
    int val;
    int poz;
};
he heap[200001];
void insert_in_heap(int x,int poz)
{
    nr++;
    heap[nr].val = x;
    heap[nr].poz = poz;//in arbore pe pozitia nr ce element se afla
    v[poz] = nr;//pozitia elementului poz in arbore
    int p = nr;
    while(p > 1 && heap[p].val < heap[p / 2].val)
{
    swap(heap[p],heap[p / 2]);
    v[heap[p].poz] = p;
    v[heap[p / 2].poz] = p / 2;
    p /= 2;
}
}
void delete_from_heap(int poz)
{
    int p = v[poz];
    swap(heap[p],heap[nr]);
    v[heap[p].poz] = p;
    nr--;
    while(p * 2 + 1 <= nr && (heap[p * 2].val < heap[p].val or  heap[p * 2 + 1].val < heap[p].val))
    {
        if(heap[p * 2].val < heap[p * 2 + 1].val)
        {
            swap(heap[p],heap[p * 2]);
        v[heap[p].poz] = p;
        v[heap[p * 2].poz] = p * 2;
        p *= 2;
        }
else
{
            swap(heap[p],heap[p * 2+1]);
        v[heap[p].poz] = p;
        v[heap[p * 2+1].poz] = p * 2+1;
        p *= 2;
        p++;
}
}
if(p * 2 == nr && heap[p * 2].val < heap[p].val)
    {
        swap(heap[p],heap[p * 2]);
    v[heap[p].poz] = p;
    v[heap[p * 2].poz] = p * 2;
    p *= 2;
    }

}
void caut_min()
{
    g<<heap[1].val<<"\n";
}
int main()
{
    int n=0;
    f>>n;
    int c;
    int m;
    int cnt=0;
    for(int i=1;i<=n;i++)
    {
        f>>c;
        if(c==1)
        {
            f>>m;
            cnt++;
            insert_in_heap(m,cnt);
        }
        else if(c==2)
        {
            f>>m;
            delete_from_heap(m);
        }
        else
        {
            caut_min();
        }
    }
}