Cod sursa(job #2751590)

Utilizator MihaiLazar26Lazar Mihai MihaiLazar26 Data 15 mai 2021 12:26:12
Problema Zeap Scor 20
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.44 kb
#include <iostream>
#include <fstream>
#include <set>
#include <queue>
#include <cmath>
using namespace std;
ifstream fin("zeap.in");
ofstream fout("zeap.out");



struct pereche
{
    int a, b;
    pereche(int a = 0, int b = 0)
    {
        this->a = a;
        this->b = b;
    }

    pereche& operator=(const pereche& per)
    {
        if(this != &per)
        {
            this->a = per.a;
            this->b = per.b;
        }
        return *this;
    }

    bool operator<(const pereche& per) const
    {
        return abs(this->a - this->b) < abs(per.a - per.b);
    }

    bool operator>(const pereche& per) const
    {
        return abs(this->a - this->b) > abs(per.a - per.b);
    }
};

priority_queue<pereche, vector<pereche>, greater<pereche>> PQ;

set<int> Z;

void update(int x)
{
    auto ir = Z.find(x);
    int minim = 1000000010, nr = x;
    for(auto it = Z.begin(); it != Z.end(); it++)
        if(*it != *ir && abs(*it - x) < minim)
    {
        minim = abs(*it - x);
        nr = *it;
    }
    if(nr != x) PQ.push(pereche(x, nr));
}

void inserare(int x)
{
    if(!Z.count(x))
    {
        Z.insert(x);
        update(x);


    }
}

int stergere(int x)
{
    if(Z.count(x))
    {
        Z.erase(x);
        return 1;
    }
    return -1;
}

int cauta(int x)
{
    if(Z.count(x)) return 1;
    return 0;
}

int minim()
{
    if(Z.size() < 2) return -1;

    pereche x = PQ.top();
    while(!Z.count(x.a) || !Z.count(x.b))
    {
        PQ.pop();
        if(Z.count(x.a)) update(x.a);
        else if (Z.count(x.b)) update(x.b);
        x = PQ.top();
    }
    return abs(x.a - x.b);
}

int maxim()
{
    if(Z.size() < 2) return -1;
    auto minim = Z.begin();
    auto maxim = Z.rbegin();
    return abs(*minim - *maxim);
}

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<<maxim()<<"\n";
        }
        else if(comanda == "MIN")
        {
            fout<<minim()<<"\n";
        }
    }
}