Cod sursa(job #989944)

Utilizator gunner_292Mihai Manolescu gunner_292 Data 26 august 2013 22:42:21
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 2.21 kb
#include<fstream>
#include<list>
#define dmax 200003

using namespace std;

ifstream in("heapuri.in");
ofstream out("heapuri.out");

int n;

int heap[dmax];
int length = -1;

int hp[dmax];
int ip[dmax];

int nr = -1;
int nin[dmax];

void hSwap(int p1, int p2)
{
    int t;
    t = heap[p1];
    heap[p1] = heap[p2];
    heap[p2] = t;

    int i1 = hp[p1];
    int i2 = hp[p2];

    t = hp[p1];
    hp[p1] = hp[p2];
    hp[p2] = t;

    t = ip[i1];
    ip[i1] = ip[i2];
    ip[i2] = t;

}



void up(int pos)
{
    if(pos <= 0)
        return;

    int father = pos/2;

    if(heap[father] > heap[pos])
    {
        hSwap(pos, father);
        up(father);
    }
}




void down(int pos)
{
    if(pos > length/2)
        return;

    int left, right;

    left = 2*pos;
    right = 2*pos+1;

    int mn = pos;

    if(left <= length && heap[left] < heap[pos])
        mn = left;
    else if(right <= length && heap[right] < heap[mn])
        mn = right;

    if(mn != pos)
    {
        int t;
        hSwap(mn, pos);
        down(mn);
    }

}

void hInsert(int k)
{
    length++;
    heap[length] = k;

    nr++;
    nin[nr] = k;

    hp[length] = nr;
    ip[nr] = length;

    up(length);
}

void getMin()
{
    out<<heap[0]<<'\n';
}


void hRemove(int k)
{

    int pos = ip[k];

    //out<<nin[k]<<"*"<<heap[pos]<<'\n';

    hSwap(pos, length);
    length--;

    if(2*pos <=length && heap[pos] > heap[2*pos] )
        down(pos);
    if(2*pos+1 <=length && heap[pos] > heap[2*pos+1] )
        down(pos);
    else if(pos != 0 && heap[pos/2] > heap[pos])
        up(pos);
}



int main()
{
    in>>n;

    for(int i=1; i<=n; i++)
    {
        int op;

        in>>op;

        if(op == 1)
        {
            int a;
            in>>a;

            hInsert(a);
        }
        else if(op == 2)
        {
            int a;
            in>>a;

            hRemove(a-1);
        }
        else getMin();

    /*
        for(int i=0; i<=length; i++)
            out<<heap[i]<<" ";
        out<<'\n';
    /*
        for(int i=0; i<=length; i++)
            out<<hp[i]<<" ";
        out<<'\n';

        for(int i=0; i<=length; i++)
            out<<ip[i]<<" ";
        out<<'\n';

        out<<'\n';
      */
    }

    in.close();
    out.close();

    return 0;
}