Cod sursa(job #1468565)

Utilizator k_ounu_eddyIacob Eduard k_ounu_eddy Data 6 august 2015 13:11:17
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.27 kb
#include<iostream>
#include<fstream>
#define DEBUG2
#define DEBUG

using namespace std;
int heap[200001], cnt = 1;
int el[200001], cntEl = 1;
int poz[200001];

void list(int *v);

void percolate(int n)
{
    cout<<"percolate()"<<endl;

    while((n != 1) && (heap[n] < heap[n/2]))
    {
        int aux = heap[n/2];
        heap[n/2] = heap[n];
        heap[n] = aux;               

        

#ifdef DEBUG
        cout<<heap[n/2]<<" trece pe "<<n/2<<endl;
        cout<<heap[n]<<" trece pe "<<n<<endl;

        poz[n] = n/2;
        

        list(heap);
        list(el);
        list(poz);
#endif

        n = n/2;
    }

#ifdef DEBUG
    cout<<"~percolate()"<<endl;
#endif
}

void sift(int n)
{
    int max, aux=0;
#ifdef DEBUG
    cout<<"sift()"<<endl;
#endif
    if( (2*n < cnt) && heap[2*n]<heap[n])
        aux = 2*n;

    if( (2*n +1 < cnt) && heap[2*n+1]<heap[n])
        if(heap[2*n+1] < heap[2*n])
            aux = 2*n+1;
    
    while(aux!=0)
    {
#ifdef DEBUG
        cout<<"Schimb "<< aux<<" cu "<<n<<endl;
#endif

        int change = heap[n];
        heap[n] = heap[aux];
        heap[aux] = change;

        change = poz[n];
        poz[n] = aux;
        poz[aux] = change;

        n = aux;
        aux = 0;  

        if( (2*n < cnt) && heap[2*n]<heap[n])
            aux = 2*n;

        if( (2*n +1 < cnt) && heap[2*n+1]<heap[n])
            if(heap[2*n+1] < heap[2*n])
                 aux = 2*n+1;
    }
}

void list(int *v)
{
    for(int i=0;i<cnt;i++)
        cout<<v[i]<<" ";

    cout<<endl;
}

int main()
{
    fstream fin, fout;
    freopen("heapuri.in", "r", stdin);
    freopen("heapuri.out", "w", stdout);    

    int N;
    scanf("%d", &N);    

    for(int i=0;i<N;i++)
    {
        int a,b;
        scanf("%d", &a);

        if(a==1)
        {
            scanf("%d", &b);
#ifdef DEBUG
    cout<<"Adaug "<<b<<" pe pozitia "<<cnt<<endl;
#endif
            heap[cnt++] = b;
            el[cnt-1] = b;
            poz[cnt-1] = cnt-1;

#ifdef DEBUG
    list(heap);
    list(el);
    list(poz);
#endif

            percolate(cnt-1);
        } else if(a==2)
        {
            scanf("%d", &b);

            heap[b] = heap[cnt-1];
            cnt--;
        } else if(a==3)
        {
            printf("%d", heap[1]);
        }
    }
#ifdef DEBUG
    list(heap);
#endif
    return 0;
}