Cod sursa(job #2751627)

Utilizator davidbejenariu2David Bejenariu davidbejenariu2 Data 15 mai 2021 14:09:51
Problema Zeap Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.34 kb
#include <bits/stdc++.h>

using namespace std;

FILE *input;
ofstream fout("zeap.out");

class cmp {
public:
    bool operator()(pair<int, int> &X, pair<int, int> &Y) {
        return abs(X.second - X.first) > abs(Y.second - Y.first);
    }
};

priority_queue<pair<int, int>, vector<pair<int, int>>, cmp> dif;
set<int> S;

bool findNum(int x) {
    return S.find(x) != S.end();
}

void insertNum(int x) {
    if (!findNum(x)) {
        S.insert(x);

        set<int>::iterator it = S.find(x);
        set<int>::iterator it1 = it;

        if (it1 != S.begin()) {
            --it1;
            dif.push(make_pair(*it1, x));
        }

        ++it;

        if (it != S.end()) {
            dif.push(make_pair(*it, x));
        }
    }
}

int deleteNum(int x) {
    if (!findNum(x)) {
        return -1;
    }

    set<int>::iterator it = S.find(x);
    set<int>::iterator it1 = it;
    ++it1;

    if (it != S.begin() && it1 != S.end()) {
        --it;
        dif.push(make_pair(*it, *it1));
    }

    S.erase(x);
    return 1;
}

int maxDif() {
    if (S.size() < 2) {
        return -1;
    }

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

int minDif() {
    if (S.size() < 2) {
        return -1;
    }

    pair<int, int> p = dif.top();

    while (!findNum(p.first) || !findNum(p.second)) {
        dif.pop();

        if (dif.empty()) {
            return -1;
        }

        p = dif.top();
    }

    return abs(p.second - p.first);
}

int strToNum(char *command) {
    int num = 0;

    for (int i = 2; command[i] != '\n'; ++i) {
        num = num * 10 + command[i] - '0';
    }

    return num;
}

int main() {
    input = fopen("zeap.in", "r");
    char command[14];

    while (fgets(command, 13, input)) {
        if (command[0] == 'I') {
            insertNum(strToNum(command));
        } else if (command[0] == 'C') {
            fout << findNum(strToNum(command)) << '\n';
        } else if (command[0] == 'S') {
            int res = deleteNum(strToNum(command));

            if (res == -1) {
                fout << res << '\n';
            }
        } else if (!strcmp(command, "MAX\n")) {
            fout << maxDif() << '\n';
        } else {
            fout << minDif() << '\n';
        }
    }

    fclose(input);
    fout.close();

    return 0;
}