Cod sursa(job #3135138)

Utilizator LazarDanielGabrielLazar Daniel-Gabriel LazarDanielGabriel Data 1 iunie 2023 22:42:40
Problema Zeap Scor 20
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.25 kb
#include <iostream>
#include <fstream>
#include <set>
#include <climits>

using namespace std;

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

set<int> zeap;
int maxDiff = -1;
int minDiff = -1;

void inserare(int x)
{
    if (zeap.count(x) == 0)
    {
        zeap.insert(x);

        if (zeap.size() >= 2)
        {
            maxDiff = max(maxDiff, x - *zeap.begin());
            minDiff = min(minDiff, x - *zeap.begin());
            maxDiff = max(maxDiff, *zeap.rbegin() - x);
            minDiff = INT_MAX;
            auto it = zeap.begin();
            auto nextIt = next(it);
            while (nextIt != zeap.end())
            {
                minDiff = min(minDiff, *nextIt - *it);
                ++it;
                ++nextIt;
            }
        }
    }
}

int stergere(int x)
{
    if (zeap.erase(x) > 0)
    {
        if (zeap.size() < 2)
        {
            maxDiff = -1;
            minDiff = -1;
        }
        else
        {
            maxDiff = *zeap.rbegin() - *zeap.begin();
            minDiff = INT_MAX;
            auto it = zeap.begin();
            auto nextIt = next(it);
            while (nextIt != zeap.end())
            {
                minDiff = min(minDiff, *nextIt - *it);
                ++it;
                ++nextIt;
            }
        }

        return 1;
    }

    return -1;
}

int cauta(int x)
{
    return zeap.count(x) > 0 ? 1 : 0;
}

int maxDif()
{
    return maxDiff;
}

int minDif()
{
    return minDiff;
}

int main()
{
    string comanda;
    int x;
    while (fin >> comanda)
    {
        if (comanda == "I")
        {
            fin >> x;
            inserare(x);
        }
        else if (comanda == "S")
        {
            fin >> x;
            int val = stergere(x);
            if (val == -1)
                fout << -1 << "\n";
        }
        else if (comanda == "C")
        {
            fin >> x;
            fout << cauta(x) << "\n";
        }
        else if (comanda == "MAX")
        {
            fout << maxDif() << "\n";
        }
        else if (comanda == "MIN")
        {
            fout << minDif() << "\n";
        }
    }

    fin.close();
    fout.close();
    return 0;
}