Cod sursa(job #2747222)

Utilizator CalinCruceanu3576Cruceanu CalinCruceanu3576 Data 28 aprilie 2021 22:22:54
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.94 kb
#include <bits/stdc++.h>
 
using namespace std;
 
ifstream fin( "heapuri.in" );
ofstream fout( "heapuri.out" );
 
struct nod {
    int val;
 
    nod *child, *sibling;
};
 
/// h2 becomes sub-tree of h1
 
nod* merge_heap( nod* h1, nod* h2 ) {
    if( h1 == NULL ) return h2;
    if( h2 == NULL ) return h1;
 
    if( h1 -> val >= h2 -> val ) {
        h2 -> sibling = h1 -> child;
        h1 -> child = h2;
 
        return h1;
    }
    else {
        h1 -> sibling = h2 -> child;
        h2 -> child = h1;
 
        return h2;
    }
}
 
nod* two_pass_merge( nod* p ) {
    if( p == NULL || p->sibling == NULL )
        return p;
 
    nod *tmp, *a, *b;
    a = p;
    b = a -> sibling;
    tmp = b -> sibling;
 
    a -> sibling = NULL;
    b -> sibling = NULL;
 
    return merge_heap( merge_heap( a, b ), two_pass_merge( tmp ) );
}
 
void push( nod*& h, int val ) {
    nod *tmp = new nod;
 
    tmp -> val = val;
    tmp -> child = tmp -> sibling = NULL;
 
    h = merge_heap( h, tmp );
}
 
int top( nod *h1 ) {
    return h1 -> val;
}
 
void pop( nod*& h1 ) {
    nod *tmp = h1->child;
 
    /// prevent memory leaks
    delete h1;
 
    h1 = two_pass_merge( tmp );
}
 
nod *H;
unordered_map <int,int> Has;
vector <int> v;
 
int main()
{
    int N, op, x;
 
    fin >> N;
 
    for( int i = 1; i <= N; ++i ) {
        fin >> op;
        if( op == 1 ) {
            fin >> x;
            push( H, -x );
            v.push_back( x );
        }
        if( op == 2 ) {
            fin >> x;
            Has[-v[x - 1]]++;
        }
        if( op == 3 ) {
            int val = top( H );
 
            while( Has.find( val ) != Has.end() && Has[val] > 0 ) {
                pop( H );
                if( Has.find( val ) != Has.end() )
                    Has[val]--;
                val = top( H );
            }
            fout << -top( H ) << '\n';
        }
    }
    return 0;
}