Cod sursa(job #1321447)

Utilizator Alex_dudeDudescu Alexandru Alex_dude Data 19 ianuarie 2015 09:44:56
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.47 kb
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <algorithm>
#define nmax 200001
using namespace std;
FILE *f1=fopen("heapuri.in","r"),*f2=fopen("heapuri.out","w");
int h[nmax],tmp[nmax],val[nmax],n,k,x,nr;

void insereaza(int x)
{
    while(x/2 && tmp[h[x]]<tmp[h[x/2]])
    {
        swap(h[x],h[x/2]);
        val[h[x]]=x;
        val[h[x/2]]=x/2;
        x/=2;
    }
}

void sterge(int x)
{
    int y;
    while(x!=y)
    {
        y=x;

        if(2*y<=nr && tmp[h[x]]>tmp[h[2*y]]) x=2*y;
        if(2*y+1<=nr && tmp[h[x]]>tmp[h[2*y+1]]) x=2*y+1;

        swap(h[x],h[y]);

        val[h[x]]=x;
        val[h[y]]=y;
    }
}
int main()
{

    fscanf(f1,"%d",&n);
    for(int i=1;i<=n;i++)
    {
        int opt;
        fscanf(f1,"%d",&opt);
        if(opt==1)
        {
            fscanf(f1,"%d",&x);
            k++,nr++;
            tmp[k]=x;
            h[nr]=k;
            val[k]=nr;
            insereaza(nr);
        }
        else if(opt==2)
        {
            fscanf(f1,"%d",&x);
            tmp[x]=-1;
            insereaza(val[x]);

            val[h[1]]=0;
            h[1]=h[nr--];
            val[h[1]]=1;
            if(nr>1)sterge(1);
        }
        else
        {
            fprintf(f2,"%d\n",tmp[h[1]]);
        }
    }


    fclose(f1);
    fclose(f2);
    return 0;
}

//Our greatest weakness lies in giving up. The most certain way to succeed is always to try just one more time.