Cod sursa(job #2750312)

Utilizator alexbrinzaAlexandru Brinza alexbrinza Data 10 mai 2021 18:40:56
Problema Zeap Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.47 kb
#include <iostream>
#include <fstream>
#include <set>
#include <vector>
#include <queue>
#include <string>
using namespace std;

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

class cmp{

public:

    bool operator()(pair < int, int > x, pair < int, int > y)
    {
        return abs(x.first - x.second) > abs(y.first - y.second);
    }
};

set < int > Zeap;
string s;
int x, val;
priority_queue < pair < int, int > , vector < pair < int, int > > , cmp > Pairs;

bool search(int x)
{
    if(Zeap.count(x))
        return 1;
    else
        return 0;
}

void insert(int x)
{
    if(!Zeap.count(x))
    {
        Zeap.insert(x);

        if(Zeap.size() > 1)
        {
            auto pos = Zeap.find(x);
            if(pos != Zeap.begin())
            {
                auto it1 = pos;
                --it1;
                Pairs.push(make_pair(*it1, x));
            }

            auto it2 = pos;
            ++it2;
            if(it2 != Zeap.end())
                Pairs.push(make_pair(*it2, x));
        }

    }
}

int remove(int x)
{
    if(!Zeap.count(x))
        return -1;
    else
    {
        auto pos = Zeap.find(x);
        auto it1 = pos;
        ++it1;

        if(pos != Zeap.begin() && it1 != Zeap.end())
        {
            auto it2 = pos;
            --it2;

            Pairs.push(make_pair(*it1, *it2));
        }

        Zeap.erase(x);
        return 1;
    }
}

int max_dif()
{
    if(Zeap.size() < 2)
        return -1;
    else
    {
        auto it1 = Zeap.begin();
        auto it2 = Zeap.end();
        --it2;

        return *it2 - *it1;
    }
}

int min_dif()
{
    if(Zeap.size() < 2)
        return -1;

    while(!Zeap.count(Pairs.top().first) || !Zeap.count(Pairs.top().second))
    {
        Pairs.pop();
    }

    return abs(Pairs.top().first - Pairs.top().second);
}

int main()
{
    while(in >> s)
        if(s == "I")
        {
            in >> x;
            insert(x);
        }
        else if(s == "S")
             {
                in >> x;
                val = remove(x);
                if(val == -1) out << val << "\n";
             }
             else if(s == "C")
                  {
                     in >> x;
                     val = search(x);
                     out << val << "\n";
                  }
                 else if(s == "MAX")
                      {
                         out << max_dif() << "\n";
                      }
                     else {
                         out << min_dif() << "\n";
                     }
    return 0;
}