Cod sursa(job #1200539)

Utilizator armandpredaPreda Armand armandpreda Data 22 iunie 2014 19:24:33
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.93 kb
#include <cstdio>
#define MAX 200001

using namespace std;

int n,heap[MAX],nrheap,rand[MAX],urm;
void schimba(int poz1,int poz2);
void mareste(int x);
void scoate(int poz);
void coboara(int poz);
void urca(int poz);
int main()
{
    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);
    int i,op,x;
    scanf("%d",&n);
    for(i=1;i<=n;++i)
    {
        scanf("%d",&op);
        if(op==1)
        {
            scanf("%d",&x);
            urm++;
            mareste(x);
        }
        if(op==2)
        {
            scanf("%d",&x);
            scoate(x);
        }
        if(op==3)
            printf("%d\n",heap[1]);
    }
    return 0;
}
void schimba(int poz1,int poz2)
{
    int cop;
    cop=heap[poz1],heap[poz1]=heap[poz2],heap[poz2]=cop;
    cop=rand[poz1],rand[poz1]=rand[poz2],rand[poz2]=cop;
}
void mareste(int x)
{
    nrheap++;
    heap[nrheap]=x;
    rand[nrheap]=urm;
    urca(nrheap);
}
void scoate(int poz)
{
    for(int i=1;i<=nrheap;++i)
        if(rand[i]==poz)
        {
            poz=i;
            break;
        }
    schimba(poz,nrheap);
    nrheap--;
    coboara(poz);
}
void coboara(int poz)
{
    int ok=1;
    while(ok)
    {
        ok=0;
        if((poz*2+1<=nrheap and heap[poz]>heap[poz*2] and heap[poz*2]>heap[poz*2+1]) or (poz*2<=nrheap and heap[poz]>heap[poz*2] and poz*2+1>nrheap) or (poz*2+1<=nrheap and heap[poz]>heap[poz*2] and heap[poz]<heap[poz*2+1]))
        {
            schimba(poz,poz*2);
            poz=poz*2;
            ok=1;
        }
        if((poz*2+1<=nrheap and heap[poz]>heap[poz*2+1] and heap[poz*2+1]>heap[poz*2]) or (poz*2+1<=nrheap and heap[poz]>heap[poz*2+1] and heap[poz]<heap[poz*2]))
        {
            schimba(poz,poz*2+1);
            poz=poz*2+1;
            ok=1;
        }
    }
}
void urca(int poz)
{
    while(heap[poz]<heap[poz/2] and poz/2>=1)
        schimba(poz,poz/2),poz=poz/2;
}