Cod sursa(job #386975)

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

/*
 *
 */
using namespace std;
int N=-1, N2=-1;
int Heap[NMax], Position[NMax], Element[NMax];
inline void swap( int& x, int& y )
{
    x+=y;
    y=x-y;
    x-=y;
}
void sift( int k  )
{
    int son, right_son;
    while( true )
    {
        son=2*k;
        if( son > N )
            break;
        right_son=2*k+1;
        if( right_son <= N && Element[Heap[right_son]] < Element[Heap[son]] )
            son=right_son;
        if( Element[Heap[son]] >= Element[Heap[k]] )
            break;
        swap( Heap[son], Heap[k] );
        swap( Position[son], Position[k] );
        k=son;
    }
}
void percolate( int k )
{
    int key=Heap[k], f=k/2;
    while( k > 1 && Element[key] < Element[Heap[f]] )
    {
        Position[Heap[k]]=Position[Heap[f]];
        Heap[k]=Heap[f];
        k=f;
        f=k/2;
    }
    Heap[k]=key;
}
void cut( int k )
{
    int p=Position[k];
    Position[k]=-1;
    Heap[p]=Heap[N--];
    if( p > 0 && Element[Heap[p]] < Element[Heap[p/2]] )
        percolate( p );
    else sift( p );
}
int main()
{
    int n, i, x, y;
    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 );
            }
            else cut( y );
        }
        else out<<Element[Heap[0]]<<'\n';
    }
    return 0;
}