Cod sursa(job #3273797)

Utilizator pacelaaaCiurea Pavel pacelaaa Data 3 februarie 2025 21:27:02
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.72 kb
#include <bits/stdc++.h>

using namespace std;

vector< int > h, val, poz;

void sus ( int pos ) {
  int aux;
  while ( val[ h[pos] ] < val[ h[pos / 2 ] ] && pos != 1 ) {
    poz[ h[pos] ] = pos / 2;
    poz[ h[pos /2 ] ] = pos;
    aux = h[pos];
    h[pos] = h[pos / 2];
    h[pos/2] = aux;
    pos /= 2;
  }
}

void jos ( int pos ) {
  while ( val[ h[pos] ] > min( h[2 * pos], h[2*pos + 1]) && 2* pos < h.size() - 1 ) {
    if ( val[ h[ 2*pos] ]< val[ h[2*pos + 1] ]) {
      poz[ h[pos] ] = 2 * pos;
      poz[ h[pos * 2] ] = pos;
      swap ( h[pos], h[pos * 2]);
      pos = 2 * pos;
    } else {
      poz[ h[pos] ] = 2 * pos + 1;
      poz[ h[pos * 2 + 1] ] = pos;
      swap ( h[pos], h[pos * 2 + 1]);
      pos = 2 * pos + 1;
    }
  }
  if ( 2 * pos == h.size() - 1 && h[pos] > h[ 2*pos] ) {
    poz[ h[pos] ] = 2 * pos;
    poz[ h[pos * 2] ] = pos;
    swap ( h[pos], h[pos * 2]);
  }
}

void push ( int value ) {
  val.push_back( value );
  h.push_back( val.size() - 1 );
  poz.push_back( h.size() - 1 );
  sus( (int) h.size() - 1 );
}

void pop( int t ) {
  poz[ h[h.size() -1] ] = poz[ t ];
  h[ poz[t]] = h[ h.size() - 1 ];
  h.pop_back();
  sus( poz[t] );
  jos( poz[t] );
}
int main()
{
    val.push_back(0);
    h.push_back(0);
    poz.push_back(0);
    int n, operatie, x, i;
    ifstream fin ( "heapuri.in" );
    ofstream fout ( "heapuri.out" );

    fin >> n;
    for ( i = 0; i < n; i ++ ) {
      fin >> operatie;
      if ( operatie == 1 ) {
        fin >> x;
        push ( x );
      } else if ( operatie == 2 ) {
      fin >> x;
      pop( x );
      } else
      fout << val[h[1]] << "\n";
    }

    fin.close();
    fout.close();


    return 0;
}