Cod sursa(job #1466662)

Utilizator k_ounu_eddyIacob Eduard k_ounu_eddy Data 29 iulie 2015 19:37:55
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.25 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;
    fin.open("heapuri.in");

    ofstream fout;
    fout.open("heapuri.out");
    int N;
    fin>>N;   

    for(int i=0;i<N;i++)
    {
        int a,b;
        fin>>a;

        if(a==1)
        {
            fin>>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)
        {
            fin>>b;

            heap[b] = heap[cnt-1];
            cnt--;


        } else if(a==3)
        {
            fout<<heap[1]<<endl;
        }
    }
#ifdef DEBUG
    list(heap);
#endif
    fin.close();
    fout.close();
    return 0;
}