This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
using namespace std;
#define INF 1000000009
multiset<int> upper;
multiset<int> lower;
int lsum, usum;
void build(int val) {
int median;
if(lower.empty()) {
median = INF;
}
else{
median = *lower.rbegin();
}
if (val <= median) {
lower.insert(val);
lsum += val;
}
else {
upper.insert(val);
usum += val;
}
if (upper.size() + 1 < lower.size()) {
int moved = *lower.rbegin();
lower.erase(lower.find(moved));
upper.insert(moved);
lsum -= moved;
usum += moved;
}
else if (lower.size() < upper.size()) {
int moved = *upper.begin();
upper.erase(upper.find(moved));
lower.insert(moved);
usum -= moved;
lsum += moved;
}
}
bool comp(pair<int, int> a, pair<int, int> b) {
return a.first + a.second < b.first + b.second;
}
vector<int> pref_sum;
int main() {
int n, k;
cin >> k >> n;
pref_sum = vector<int>(n + 1);
vector<pair<int, int>> locs;
locs.push_back({0, 0});
int same = 0;
for(int i = 0; i < n; ++i) {
char a, b;
int c, d;
cin >> a >> c >> b >> d;
if(a == b) {
same += abs(c - d);
}
else {
locs.push_back({c, d});
}
}
sort(locs.begin(), locs.end(), comp);
int new_n = locs.size() - 1;
same += new_n;
for(int i = 1; i <= new_n; ++i) {
build(locs[i].first);
build(locs[i].second);
pref_sum[i] = usum - lsum;
}
int ans = pref_sum[new_n];
if (k == 2) {
lower.clear();
upper.clear();
lsum = 0;
usum = 0;
for (int i = new_n; i > 0; i--) {
build(locs[i].first);
build(locs[i].second);
ans = min(ans, usum - lsum + pref_sum[i - 1]);
}
}
cout << same + ans << endl;
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |