Cod sursa(job #387081)

Utilizator alexandru92alexandru alexandru92 Data 26 ianuarie 2010 19:56:05
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.64 kb
/* 
 * File:   main.cpp
 * Author: virtualdemon
 *
 * Created on January 25, 2010, 6:05 PM
 */
#include <fstream>
#define NMax 200010

/*
 *
 */
using namespace std;
int N=0, N2=0;
int Heap[NMax], Element[NMax];
inline void swap( int& x, int& y )
{
    x+=y;
    y=x-y;
    x-=y;
}
void sift( int k )
{
    int son;
    while( true )
    {
        son=2*k;
        if( son > N )
            break;
        if( 2*k+1 <= N && Element[Heap[2*k+1]] < Element[Heap[son]] )
            son=2*k+1;
        if( Element[Heap[son]] >= Element[Heap[k]] )
            break;
        swap( Heap[son], Heap[k] );
        k=son;
    }
}
void percolate( int k )
{
    int key=Heap[k], f=k/2;
    while( k > 1 && Element[key] < Element[Heap[f]]   )
    {
        Heap[k]=Heap[f];
        k=f;
        f/=2;
    }
    Heap[k]=key;
}
int main()
{int n, i, x, y, k;
    ifstream in("heapuri.in");
    ofstream out("heapuri.out");
    in>>n;
    for( i=0; i < n; ++i )
    {
        in>>x;
        if( x < 3 )
        {
            in>>y;
            if( 1 == x )
            {
                Element[++N2]=y;
                Heap[++N]=N2;
                percolate( N );
                continue;
            }
            if( 2 == x )
            {
                for( k=0; k < N; ++k )
                    if( Element[Heap[k]] == Element[y] )
                        break;
                Heap[k]=Heap[N];
                --N;
                if( k > 1 && Element[Heap[k]] < Element[Heap[k/2]] )
                    percolate( k );
                else sift( k );
                continue;
            }
            continue;
        }
        out<<Element[Heap[1]]<<'\n';
    }
    return 0;
}