Cod sursa(job #3135630)

Utilizator alexandramocanu181Mocanu Alexandra alexandramocanu181 Data 3 iunie 2023 21:01:30
Problema Zeap Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2 kb
#include <iostream>
#include <fstream>
#include <set>
#include <vector>
#include <algorithm>

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

std::set<int> zeap;
std::vector<std::string> output;

void insertElement(int x)
{
    zeap.insert(x);
}

int deleteElement(int x)
{
    if (zeap.find(x) != zeap.end())
    {
        zeap.erase(x);
    }
    else
    {
        return -1;
    }
    return 0;
}

int searchElement(int x)
{
    return zeap.count(x);
}

int maxDifference()
{
    if (zeap.size() < 2)
    {
        return -1;
    }
    return *(--zeap.end()) - *(zeap.begin());
}

int minDifference()
{
    if (zeap.size() < 2)
    {
        return -1;
    }
    std::vector<int> sortedZeap(zeap.begin(), zeap.end());
    std::sort(sortedZeap.begin(), sortedZeap.end());
    int minDiff = sortedZeap[1] - sortedZeap[0];
    for (int i = 2; i < sortedZeap.size(); i++)
    {
        minDiff = std::min(minDiff, sortedZeap[i] - sortedZeap[i - 1]);
    }
    return minDiff;
}

int main()
{
    std::string line;
    while (std::getline(fin, line))
    {
        char operation;
        int arg;
        std::stringstream ss(line);
        ss >> operation >> arg;

        if (operation == 'I')
        {
            insertElement(arg);
        }
        else if (operation == 'D')
        {
            int result = deleteElement(arg);
            if (result != -1)
            {
                output.push_back(std::to_string(result));
            }
        }
        else if (operation == 'S')
        {
            output.push_back(std::to_string(searchElement(arg)));
        }
        else if (operation == 'M')
        {
            output.push_back(std::to_string(maxDifference()));
        }
        else if (operation == 'N')
        {
            output.push_back(std::to_string(minDifference()));
        }
    }

    for (const std::string& str : output)
    {
        fout << str << "\n";
    }

    return 0;
}