Cod sursa(job #2899782)

Utilizator PatrascuAdrian1Patrascu Adrian Octavian PatrascuAdrian1 Data 9 mai 2022 01:22:49
Problema Zeap Scor 40
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.2 kb
#include <bits/stdc++.h>

using namespace std;

ofstream out("zeap.out");

using pii = pair<int,int>;
using piii = pair<int,pii>;
set<int> Z;
priority_queue<piii> Q;

int parse(string S)
{
    int x = 0;
    for(int i = 0; i < S.size() - 1; ++i)
        x = x * 10 + S[i] - '0';
    return x;
}

void Insert(int x)
{
    if(Z.find(x) == Z.end())
    {
        Z.insert(x);
        if(Z.size() >= 2)
        {
            auto it = Z.find(x);
            if(it != Z.begin())
            {
                it--;
                Q.push({abs(x - *it) * -1, {*it, x}});
            }
            it = Z.find(x);
            if(it != Z.end())
            {
                it++;
                Q.push({abs(*it - x) * -1, {*it, x}});
            }
        }
    }
}

void Delete(int x)
{
    if(Z.find(x) == Z.end())
        out << "-1 \n";
    else
    {
        auto it = Z.find(x);
        auto right = it;
        right++;
        if(it == Z.begin() || right == Z.end())
            Z.erase(x);
        else
        {
            auto left = it;
            left--;
            if (right != Z.end() && it != Z.begin())
                Q.push({abs(*right - *left) * -1, {*left, *right}});
            Z.erase(x);
        }
    }
}

void Search(int x)
{
    out << (Z.find(x) == Z.end() ? 0 : 1) << '\n';
}

void MIN()
{
    if(Z.size() < 2)
        out << -1 << '\n';
    else
    {
        while(Z.find(Q.top().second.first) == Z.end() || Z.find(Q.top().second.second) == Z.end())
            Q.pop();
        out <<  -1 * Q.top().first << '\n';
    }
}

void MAX()
{
    if(Z.size() < 2)
        out << -1 << '\n';
    else
    {
        auto left = Z.begin(), right = Z.end();
        right--;
        out << *right - *left << '\n';
    }
}

int main()
{
    char S[10];
    FILE* in = fopen("zeap.in", "r");
    while(fgets(S, sizeof(S), in))
    {
        if(S[0] == 'I')
            Insert(parse(S + 2));
        else if(S[0] == 'S')
            Delete(parse(S + 2));
        else if(S[0] == 'C')
            Search(parse(S + 2));
        else if(S[1] == 'I')
            MIN();
        else
            MAX();
    }
    return 0;
}