Cod sursa(job #3135082)

Utilizator Alexandra789Alexandra Uceanu Alexandra789 Data 1 iunie 2023 19:05:36
Problema Zeap Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.2 kb
#include <iostream>
#include <fstream>
#include <set>
#include <queue>

void insereaza(std::set<int>& s, std::priority_queue<std::pair<int, std::pair<int, int>>>& pq, int x){
    s.insert(x);

    auto it = s.find(x);

    auto it2 = s.upper_bound(x);
    if(it2 != s.end())
        pq.push({*it - *it2, {*it, *it2}});

    it2 = s.lower_bound(x);
    if(it2 != s.begin()){
        --it2;
        pq.push({*it2 - *it, {*it, *it2}});
    }
}

int sterge(std::set<int>& s, std::priority_queue<std::pair<int, std::pair<int, int>>>& pq, int x){
    if(s.find(x) == s.end())
        return -1;

    auto it = s.find(x);
    auto it2 = it;

    if(it2 != s.begin()){
        --it2;
        ++it;
        if(it != s.end())
            pq.push({*it2 - *it, {*it, *it2}});
    }
    
    s.erase(x);
    return 1;
}

int cauta(const std::set<int>& s, int x){
    if(s.find(x) == s.end())
        return 0;
    return 1;
}

int maxDif(const std::set<int>& s){
    if(s.size() < 2)
        return -1;

    return *(s.rbegin()) - *(s.begin());
}

int minDif(const std::set<int>& s, std::priority_queue<std::pair<int, std::pair<int, int>>>& pq){
    while(!pq.empty() && (s.find(pq.top().second.first) == s.end() || s.find(pq.top().second.second) == s.end())){
        pq.pop();
    }

    if(pq.empty())
        return -1;
    return -pq.top().first;  
}

int main(){
    std::ifstream f("zeap.in");
    std::ofstream g("zeap.out");

    std::set<int> zeap1;
    std::priority_queue<std::pair<int, std::pair<int, int>>> zeap2;

    char op;
    while(f >> op){
        if(op == 'I'){
            int x;
            f >> x;
            insereaza(zeap1, zeap2, x);
        }
        else if(op == 'S'){
            int x;
            f >> x;
            if(sterge(zeap1, zeap2, x) == -1)
                g << -1 << '\n';
        }
        else if(op == 'C'){
            int x;
            f >> x;
            g << cauta(zeap1, x) << '\n';
        }
        else if(op == 'M'){
            f >> op;

            if(op == 'A')
                g << maxDif(zeap1) << '\n';
            else
                g << minDif(zeap1, zeap2) << '\n';
        }
    }
    return 0;
}