Cod sursa(job #1217839)

Utilizator ArkinyStoica Alex Arkiny Data 8 august 2014 14:01:33
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 2.84 kb
#include<iostream>
#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!=1 && heap[position/2] > heap[position])
        {
          swapHeap(position,position/2);
          position=position/2;
        }
         
         
    }
    void order_down(int position)
    {
        int child;
        do
        {
              if((position*2+1)<i)
              {
                 child = (heap[position*2] < heap[position*2+1]) ? position*2 : (position*2 + 1);
              }
              else
              {
                 child=position*2;
                  
              }
            if(heap[position]>heap[child])
            {
              swapHeap(position,child);
 
              position=child;
			}
        }while(position*2<i);
 
        }
    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 > 1 && heap[position/2]>heap[position])
        {
            do
            {
               swapHeap(position,position/2);
               position=position/2;
            }while(position!=1 && heap[position/2] > heap[position]);
        }
        else
        {
            int child;
              do
              {
				   if(position*2<i)
				   {
					 if((position*2+1)<i)
					 {
						 child = (heap[position*2] < heap[position*2+1]) ? position*2 : (position*2 + 1);
					 }
					 else
				     {
						 child=position*2;
                  
                     }
					if(heap[position]>heap[child])
						{
							 swapHeap(position,child);
 
							 position=child;
						}
					else
						break;
				   }
             }while(position*2<i);
       }
    }
 
 
 
 
 
int main()
{
    ifstream f("heapuri.in");
    ofstream fo("heapuri.out");
    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();
    return 0;
}