You are viewing a single comment's thread. Return to all comments →
void balance(multiset<long>& lower, multiset<long>& upper) { if (lower.size() > upper.size() + 1) { upper.insert(*lower.rbegin()); auto rit = lower.rbegin(); auto it = rit.base(); lower.erase(--it); } else if (lower.size() + 1 < upper.size()) { lower.insert(*upper.begin()); upper.erase(upper.begin()); } } void median(vector<char> s, vector<int> X) { multiset<long> lower = { -3000000000 }; multiset<long> upper = { 3000000000 }; for (int i = 0; i < s.size(); i++) { if (s[i] == 'a') { if (X[i] <= *lower.rbegin()) { lower.insert(X[i]); } else { upper.insert(X[i]); } } if (s[i] == 'r') { if (X[i] <= *lower.rbegin()) { auto it = lower.find(X[i]); if (it != lower.end()) { lower.erase(it); } else { cout << "Wrong!" << "\n"; continue; } } else if (X[i] >= *upper.begin()) { auto it = upper.find(X[i]); if (it != upper.end()) { upper.erase(it); } else { cout << "Wrong!" << "\n"; continue; } } else { cout << "Wrong!" << "\n"; continue; } } balance(lower, upper); if (lower.size() == upper.size() + 1) { cout << *lower.rbegin() << "\n"; } else if (lower.size() + 1 == upper.size()) { cout << *upper.begin() << "\n"; } else if (lower.size() == upper.size() and lower.size() != 1) { long long a = *lower.rbegin(); long long b = *upper.begin(); if ((a + b) % 2 == 0) { cout << std::fixed << std::setprecision(0) << (a + b) / 2.0 << "\n"; } else { cout << std::fixed << std::setprecision(1) << (a + b) / 2.0 << "\n"; } } else { cout << "Wrong!" << "\n"; } } }
Seems like cookies are disabled on this browser, please enable them to open this website
Median Updates
You are viewing a single comment's thread. Return to all comments →