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 <bits/stdc++.h>
using namespace std;
using i64 = long long;
const i64 INF = 1E18;
char ch[2];
int x[2];
template <typename T>
ostream& operator<< (ostream &out, vector <T> vec) {
out << "{";
for(int i = 0; i < int(vec.size()); i++) {
out << vec[i];
if(i +1 < int(vec.size())) {
out << ", ";
}
}
return out << "}";
}
#define ONLINE_JUDGE
i64 suml = 0, sumr = 0;
multiset <int> low, up;
void balance() {
while(int(low.size()) > int(up.size())) {
int x = *low.rbegin();
up.emplace(x);
suml -= x;
sumr += x;
low.erase(low.find(x));
}
while(int(up.size()) > int(low.size())) {
int x = *up.begin();
low.emplace(x);
suml += x;
sumr -= x;
up.erase(up.find(x));
}
}
void add(int x) {
low.emplace(x);
suml += x;
balance();
}
void solve() {
int k, n;
cin >> k >> n;
i64 total = 0;
vector <pair <int, int>> a;
for(int i = 0; i < n; i++) {
cin >> ch[0] >> x[0] >> ch[1] >> x[1];
if(ch[0] != ch[1]) {
a.emplace_back(x[0], x[1]);
} else {
total += abs(x[0] - x[1]);
}
}
n = int(a.size());
i64 ans = INF;
sort(a.begin(), a.end(), [&](pair <int, int> a, pair <int, int> b) -> bool {
return a.second + a.first < b.second + b.first;
});
vector <i64> pref(n +1);
for(int i = 0; i < n; i++) {
add(a[i].first);
add(a[i].second);
//cerr << a[i].first << " " << a[i].second << " :: " << sumr << " " << suml << "\n";
pref[i +1] = sumr - suml;
}
ans = min(ans, pref[n]);
if(k == 2) {
low.clear();
up.clear();
suml = sumr = 0;
for(int i = n; i >= 1; i--) {
add(a[i -1].first);
add(a[i -1].second);
//cerr << a[i].first << " " << a[i].second << " :: " << sumr << " " << suml << " | " << pref[i -1] << "\n";
ans = min(ans, pref[i -1] + sumr - suml);
}
}
cout << ans + total + n;
}
signed main() {
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
solve();
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... |