Cod sursa(job #2080126)

Utilizator eduardandrei20Nechifor Eduard Andrei eduardandrei20 Data 2 decembrie 2017 14:38:50
Problema Heapuri Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 2.77 kb
#include <iostream>
//heapuri
#include <bits/stdc++.h>
using namespace std;
ifstream in("heapuri.in");
ofstream out("heapuri.out");
inline int father(int nod); inline int left_son(int nod); inline int right_son(int nod );
int heap[200000] , op , n  ;
int ordine[10000000];
int loc ;
void percolate(int pozitie, int valoare )
{

while ( pozitie > 1 && heap[pozitie] < heap[father(pozitie)])
{
    swap(heap[pozitie],heap[father(pozitie)]);
    pozitie= father(pozitie);
}
}

void sift ( int pozitie , int valoare )
{
    while ( 1)

    {

         bool stanga = false ; bool dreapta = false;
        if(left_son(pozitie) <= n ) stanga = true ;
        if(right_son(pozitie)<=n )dreapta = true ;
           if ( (left_son(pozitie)>n || heap[pozitie]<=heap[left_son(pozitie)])
                && (right_son(pozitie) > n || heap [pozitie] <= heap[right_son(pozitie)])) break;
        if(stanga == true && dreapta == false && heap[pozitie]>heap[left_son(pozitie)])
        {swap(heap[pozitie],heap[left_son(pozitie)]);
          pozitie=left_son(pozitie);}

        if(dreapta == true && stanga == false && heap[pozitie]>heap[right_son(pozitie)])
        {
            swap(heap[pozitie],heap[right_son(pozitie)]);
            pozitie= right_son(pozitie);
        }
      if( dreapta == true && stanga == true )
      {
          int who ;
          if( heap[left_son(pozitie)]<heap[right_son(pozitie)])
          {
              swap(heap[pozitie],heap[left_son(pozitie)]);
              pozitie=left_son(pozitie);
          }
          else {swap(heap[pozitie],heap[right_son(pozitie)]);
          pozitie = right_son(pozitie);}
      }
    }
}





void insert_function(int val)
{

    ++ n ;
    heap[n] = val ;
percolate(n,val);
}






inline int father(int nod)
{
    return nod/2;
}

inline int left_son(int nod)
{
    return nod*2;
}

inline int right_son(int nod)
{
    return nod*2+1;
}


void build_heap()
{
    for ( int i = n / 2 ; i > 0 ; -- i )
        sift(i,heap[i]);
}

void cut (int pozitie , int valoare )
{

    heap[pozitie] = heap[n];
    -- n ;

    if(heap[pozitie] > heap[father(pozitie)] )
    percolate(pozitie,heap[pozitie]);
    else sift(pozitie,heap[pozitie]);
}




int main()
{
in >> op;
for ( int i =1 ; i <= op ; ++ i )
{
for(int a =1 ; a <= n ;++ a )cout <<heap[a]<<" ";
cout << endl ;
    int ce_fac;
    in >> ce_fac;
    if(ce_fac==1){int x;
    in >> x ;
    insert_function(x);
    ordine[++loc]=x;
    }
    else if(ce_fac==2){
int x ;
in >> x ;
int value= ordine[x];
int poz;
for(int j =1 ; j<= n ; ++ j )
    if(heap[j]==value)
{
    poz = j ; break; }

cut(poz,value);

    }

else {
        build_heap();out << heap[1]<<"\n";}


}


    return 0;
}