Cod sursa(job #797733)

Utilizator danalex97Dan H Alexandru danalex97 Data 14 octombrie 2012 18:53:14
Problema Zeap Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.41 kb
#include <fstream>
#include <cstring>
#include <set>
#include <map>
using namespace std;

ifstream F("zeap.in");
ofstream G("zeap.out");

const int Nmax = 20;

char Str[Nmax];

set<int> A;
map<int,int> D;
typedef set<int>::iterator IT;

int Get()
{
    int Act=2,Nbr=0;
    while ( Str[Act]>='0' && Str[Act]<='9' )
        Nbr=Nbr*10+Str[Act++]-'0';
    return Nbr;
}

void Insert()
{
    int Nbr = Get();

    if ( A.empty() )
    {
        A.insert( Nbr );
        return;
    }

    A.insert( Nbr );
    IT Low , Up , Mid ;
    Low = Up = Mid = A.find( Nbr );
    ++Up;

    if ( Mid == A.begin() )
    {
        ++D[ *Up - *Mid ];
        return;
    }

    --Low;
    if ( Up == A.end() )
    {
        ++D[ *Mid - *Low ];
        return;
    }

    if ( --D[*Up - *Low] == 0 ) D.erase(*Up - *Low);
    ++D[ *Up - *Mid ];
    ++D[ *Mid - *Low ];
}

void Delete()
{
    int Nbr = Get();
    if ( A.find( Nbr ) == A.end() )
    {
        G<<"-1\n";
        return;
    }

    IT Low , Up , Mid ;
    Low = Up = Mid = A.find( Nbr );
    --Low , ++Up;

    if ( Mid == A.begin() && Up == A.end() )
    {
        A.erase( Nbr );
        return;
    }

    if ( Mid == A.begin() )
    {
        if ( --D[ *Up - *Mid ] == 0 )
            D.erase( *Up - *Mid );
        return;
    }
    if ( Up == A.end() )
    {
        if ( --D[ *Mid - *Low ] == 0 )
            D.erase( *Mid - *Low );
        return;
    }

    if ( --D[ *Up - *Mid ] == 0) D.erase( *Up - *Mid );
    if ( --D[ *Mid - *Low ] == 0) D.erase( *Mid - *Low );
    ++D[ *Up - *Low ];

    A.erase( Mid );
}

void Find()
{
    int Nbr = Get();
    G<<( A.find(Nbr) != A.end() )<<'\n';
}

void Max()
{
    int Low = *A.begin() ,Up = *A.rbegin();
    G<<( Up - Low )<<'\n';
}

void Min()
{
    G<<( D.begin()->first )<<'\n';
}

int main()
{
    while ( F.getline(Str,Nmax,'\n') )
    {
        if ( Str[0] == 'I' )
        {
            Insert();
            continue;
        }
        if ( Str[0] == 'S' )
        {
            Delete();
            continue;
        }
        if ( Str[0] == 'C' )
        {
            Find();
            continue;
        }
        if ( A.size() < 2 )
        {
            G<<"-1\n";
            continue;
        }
        if ( Str[0] == 'M' && Str[1] == 'A' )
            Max();
        else
            Min();
    }
}