Cod sursa(job #1217862)

Utilizator ArkinyStoica Alex Arkiny Data 8 august 2014 14:44:09
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 2.29 kb
#include<fstream>
using namespace std;

    int heap[1000000];
    int i=1;
    int pos[200100];
    int t[200100];
    int pr=1;


	void swapHeap(int t1,int t2)
	{
		int aux=heap[t1];
		heap[t1]=heap[t2];
		heap[t2]=aux;

		aux=t[pos[t1]];
		t[pos[t1]]=t[pos[t2]];
		t[pos[t2]]=aux;

		aux=pos[t1];
		pos[t1]=pos[t2];
		pos[t2]=aux;
	}

    void order_up(int  position)
    {
        while(position/2 && heap[position/2] > heap[position])
        {
          swapHeap(position,position/2);
          position=position/2;
        }


    }
    void order_down(int position)
    {
        int child;
       while(position*2<i)
	   {

              if((position*2+1)<i)
              {
                  if(heap[position*2] < heap[position*2+1])
                    child=position*2;
                  else
                    child=position*2 +1;
              }
              else
              {
                 child=position*2;

              }
            if(heap[position]>heap[child])
            {
              swapHeap(position,child);

              position=child;
			}
			else
				break;
			}


     }
    void add_to_heap(int value)
    {
        heap[i]=value;
        pos[i]=pr;
        t[pr]=i;
        order_up(i++);
        ++pr;
    }

    void delete_from_heap(int id)
    {

        int position=t[id];
        swapHeap(position,i-1);

        --i;
        if(position/2 && heap[position/2]>heap[position])
        {
            order_up(position);
        }
        else
        {
            order_down(position);
        }
    }




void exec(const char *name_i,const char *name_o)
{
    ifstream f(name_i);
    ofstream fo(name_o);
    int lines;
    f>>lines;
    int operation;
    for(int j=1;j<=lines;j++)
    {
        f>>operation;
        if(operation==1)
        {
            int  value;
            f>>value;
            add_to_heap(value);

        }else if(operation==2)
        {
            int elem;
            f>>elem;
            delete_from_heap(elem);
        }
        else if(operation==3)
        {
            if(i>1)
             fo<<heap[1]<<endl;

        }
    }
    f.close();
    fo.close();
}

int main()
{
    exec("heapuri.in","heapuri.out");
    return 0;
}