Cod sursa(job #2840909)

Utilizator KarinaDKarina Dumitrescu KarinaD Data 28 ianuarie 2022 23:24:25
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.82 kb
#include <fstream>

using namespace std;

const int N = 200000;
int heap [ N ], v [ N ];

int main( ) {
    
    ifstream fin ( "heapuri.in" );
    ofstream fout ( "heapuri.out" );
    
    int n, a, i, k = 1, h = 1, x;
    
    fin >> n;
    
    for ( i = 0; i < n; i++ ){
        
        fin >> a;
        
        if ( a == 1 ){
            
            fin >> v [ k ];
            k++;
            
            x = h;
            heap [ x ] = v [ k - 1 ];
            
            while ( heap [ x ] < heap [ x / 2 ] && x > 0 ){
                
                heap [ x ] = heap [ x / 2 ];
                heap [ x / 2 ] = v [ k - 1 ];
                
                x = x / 2;
            }
            
            h++;
            
        }
        
        else if ( a == 2 ){
            
            fin >> x;
            
            a = 1;
            
            while ( heap [ a ] < v [ x ] )
                a = a * 2;
            
            while ( heap [ a ] != v [ x ] )
                a++;
            
            heap [ a ] = heap [ h ];
            heap [ h ] = v [ x ];
            
            x = heap [ a ];
            
            
            while ( a < h ){
                
                if ( heap [ 2 * a ] < heap [ 2 * a + 1 ] && x > heap [ 2 * a ] ){
                    heap [ 2 * a ] = heap [ a ];
                    heap [ 2 * a ] = x;
                }
                
                else if ( heap [ 2 * a ] > heap [ 2 * a + 1 ] && x > heap [ 2 * a + 1 ] ){
                    heap [ 2 * a ] = heap [ a ];
                    heap [ 2 * a ] = x;
                    a++;
                }
                    
                a = a * 2;
            }
            
            h--;
            
        }
        
        else
            fout << heap [ 1 ] << "\n";
            
    }
    
    return 0;
}