Cod sursa(job #949698)

Utilizator DDeidaraSzasz Tamas Csaba DDeidara Data 14 mai 2013 18:32:23
Problema Heapuri Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 2.02 kb
#include<cstdio>

typedef int Heap[200001];

inline int minim(Heap h)
{
    return h[1];
}

inline int father(int node)
{
    return node/2;
}

inline int left_son(int node)
{
    return node*2;
}

inline int right_son(int node)
{
    return node*2 + 1;
}


Heap h = {0};
int a[200001] = {0};

void sift(Heap h ,int N ,int K)
{
    int son;
    int c;

    do
    {
        son = 0;
        if (left_son(K) <= N)
        {
            son = left_son(K);

            if (right_son(K) <= N && h[right_son(K)] < h[left_son(K)])
                son = right_son(K);

            if (h[son] >= h[K])
                son = 0;
        }

        if (son)
        {
            c = h[K];
            h[K] = h[son];
            h[son] = c;
            c = a[K];
            a[K] = a[son];
            a[son] = c;
        }
    }
    while (son);
}

void percolate(Heap h ,int N , int K)
{
    int key = h[K];
    int c;

    while ( (K>1) && (key < h[father(K)]) )
    {
        h[K] = h[father(K)];
        c = a[K];
        a[K] = a[father(K)];
        a[father(K)] = c;
        K = father(K);
    }

    h[K] = key;
}

void cut (Heap h, int &N, int K)
{
    h[K] = h[N];
    --N;

    if ( (K>1) && (h[K] < h[father(K)]) ) percolate(h,N,K);
    else sift(h,N,K);
}

void insertH (Heap h,int &N,int K)
{
    h[++N] = K;
    a[N] = N;
    percolate(h,N,N);
}

int main()
{
    int N = 0;
    int t;

    int op,x;

    FILE *f,*g;

    f = fopen("heapuri.in","r");
    g = fopen("heapuri.out","w");

    fscanf(f,"%d",&t);

    for (int i=1;i<=t;i++)
    {
        fscanf(f,"%d",&op);
        if (op==1)
        {
            fscanf(f,"%d",&x);
            insertH(h,N,x);
        }
        else if (op==2)
        {
            fscanf(f,"%d",&x);
            for (int j=1;j<=N;j++) if (a[j] == x) cut(h,N,j);
        }
        else
        {
            fprintf(g,"%d\n",minim(h));
        }
    }

    fclose(f);
    fclose(g);

    return 0;
}