Pagini recente » Cod sursa (job #814512) | Cod sursa (job #1327079) | Cod sursa (job #2815485) | Cod sursa (job #1784018) | Cod sursa (job #3135896)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("zeap.in");
ofstream fout("zeap.out");
struct Comparison {
bool operator()(const pair<int, int>& a, const pair<int, int>& b) {
return abs(a.first - a.second) > abs(b.first - b.second);
}
};
set<int> zeap;
priority_queue<pair<int, int>, vector<pair<int, int>>, Comparison> minDiff;
// Inserează un element în set și actualizează coada de priorități
void insertElement(int val) {
if (zeap.count(val) == 0) {
zeap.insert(val);
set<int>::iterator successor, predecessor;
successor = zeap.find(val);
predecessor = zeap.find(val);
successor++;
if (predecessor != zeap.begin()) {
predecessor--;
minDiff.push(make_pair(val, *predecessor));
}
if (successor != zeap.end())
minDiff.push(make_pair(*successor, val));
}
}
// Șterge un element din set și actualizează coada de priorități
int deleteElement(int val) {
if (zeap.count(val) == 0) {
return -1;
} else {
set<int>::iterator it1, it2;
it1 = zeap.find(val);
it2 = zeap.find(val);
it2++;
if (it2 != zeap.end() && it1 != zeap.begin()) {
it1--;
minDiff.push(make_pair(*it2, *it1));
}
zeap.erase(val);
return 1;
}
}
// Verifică dacă un element există în set
int searchElement(int val) {
return zeap.count(val);
}
// Calculează diferența maximă între două elemente din set
int maxDifference() {
if (zeap.size() < 2)
return -1;
else {
set<int>::iterator first, last;
first = zeap.begin();
last = zeap.end();
last--;
return abs(*last - *first);
}
}
// Calculează diferența minimă între două elemente adiacente din set
int minDifference() {
if (zeap.size() < 2)
return -1;
else {
while (!(zeap.count(minDiff.top().first) == 1 && zeap.count(minDiff.top().second) == 1)) {
minDiff.pop();
}
return abs(minDiff.top().first - minDiff.top().second);
}
}
int main() {
int val;
string operation;
while (fin >> operation) {
if (operation == "I") {
fin >> val;
insertElement(val);
} else if (operation == "S") {
fin >> val;
if (deleteElement(val) == -1)
fout << -1 << '\n';
} else if (operation == "C") {
fin >> val;
fout << searchElement(val) << '\n';
} else if (operation == "MAX") {
fout << maxDifference() << '\n';
} else if (operation == "MIN") {
fout << minDifference() << '\n';
}
}
}