Cod sursa(job #1082960)

Utilizator tavi.belu1994FMI Belu Andrei Octavian tavi.belu1994 Data 15 ianuarie 2014 14:30:11
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.61 kb
#include <cstdio>
#include <algorithm>
#define nmax 200001
FILE *f,*g;
using namespace std;

int S[nmax],pos[nmax],k,k2;
int n;

int urca(int *heap, int poz)
{
    while(poz > 1 && S[heap[poz]] < S[heap[poz/2]])
    {
        swap(heap[poz] , heap[poz/2]);
        swap(pos[heap[poz]] , pos[heap[poz/2]]);
        poz /= 2;
    }
    return poz;
}

int coboara(int *heap, int &poz)
{
    int poz1;
    if (poz >= n)
        return 0;
    poz1 = poz * 2;
    if(poz1 > n)
        return 0;
    if(poz1+1 <= n && S[heap[poz1+1]] < S[heap[poz1]])
        poz1++;
    if(S[heap[poz]] > S[heap[poz1]])
    {
        swap(heap[poz] , heap[poz1]);
        swap(pos[heap[poz]] , pos[heap[poz1]]);
        coboara(heap,poz1);
    }
}

int insert_heap(int *heap, int val)
{
    heap[++n] = k;
    pos[heap[n]]=n;
    return urca(heap,n);
}

void elimina(int *heap, int poz)
{
    swap(heap[poz],heap[n--]);
    pos[heap[poz]]=poz;
    urca(heap,poz);
    coboara(heap,poz);
}

int main()
{
    f=fopen("heapuri.in","r");
    g=fopen("heapuri.out","w");
    int i,j,N,heap[nmax],x,c;
    n = 0;
    fscanf(f,"%d",&N);
    for(i=1 ; i<=N ; i++)
    {
        fscanf(f,"%d",&c);
        if(c == 1)
        {
            fscanf(f,"%d",&x);
            S[++k] = x;
            insert_heap(heap,x);
            continue;
        }
        if(c == 2)
        {
            fscanf(f,"%d",&x);
            S[heap[pos[x]]] = -1;
            elimina(heap,pos[x]);
            continue;
        }
        fprintf(g,"%d\n",S[heap[1]]);
    }
    fclose(f);
    fclose(g);
    return 0;
}