Cod sursa(job #2365118)

Utilizator tiberiu.bucur17Tiberiu Constantin Emanoil Bucur tiberiu.bucur17 Data 4 martie 2019 12:03:15
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <cstdio>
#include <algorithm>
using namespace std;
const int Maxn=200001;
int v[Maxn],poz[Maxn],heap[Maxn],l,k;
inline void up(int p)
{
    while(p/2 && v[heap[p/2]]>v[heap[p]])
    {
        swap(poz[heap[p/2]],poz[heap[p]]);
        swap(heap[p/2],heap[p]);
        p/=2;
    }
}
inline void down(int p)
{
    bool ok=true;
    int y;
    while(2*p<=l && ok)
    {
        ok=false;y=2*p;
        if(2*p+1<=l && v[heap[2*p]]>v[heap[2*p+1]])
            y++;
        if(v[heap[y]]<v[heap[p]])
        {
            swap(poz[heap[y]],poz[heap[p]]);
            swap(heap[y],heap[p]);
            p=y;ok=true;
        }
    }
}
inline void add(int x)
{
    heap[++l]=k;poz[k]=l;
    up(l);
}
inline void pop(int p)
{
    heap[p]=heap[l];
    poz[heap[l]]=p;
    l--;down(p);
}
int main()
{
    FILE *fin,*fout;
    fin=fopen("heapuri.in","r");
    fout=fopen("heapuri.out","w");
    int n,tip,x;
    fscanf(fin,"%d",&n);
    for(int i=0;i<n;i++)
    {
        fscanf(fin,"%d",&tip);
        if(tip==3)
            fprintf(fout,"%d\n",v[heap[1]]);
        else
        {
            fscanf(fin,"%d",&x);
            if(tip==1)
            {
                v[++k]=x;
                add(x);
            }
            else
                pop(poz[x]);
        }
    }
    return 0;
}