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;
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
template <class T>
using indexedset = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
typedef long long ll;
int main(){
int k, n;
cin >> k >> n;
vector<pair<ll, ll>> deals;
ll ans = 0;
for (int i = 0; i < n; i++){
char a, b;
ll c, d;
cin >> a >> c >> b >> d;
if (a == b) ans += max(d,c)-min(d,c);
else deals.push_back({min(c,d), max(c,d)});
}
ans += deals.size();
if (k == 1){
vector<ll> v;
for (auto x : deals) v.push_back(x.first), v.push_back(x.second);
sort(v.begin(), v.end());
ll med = v[v.size()/2];
for (ll x : v) ans += abs(x-med);
}else{
sort(deals.begin(), deals.end(), [&](auto x, auto y){
return (x.first+x.second)<(y.first+y.second);
});
n = (int) deals.size();
ll prefix[n+1];
ll suffix[n+1];
prefix[0] = suffix[n] = 0;
ll sum = 0;
ll other = 0;
multiset<ll> values;
for (int i = 0; i < n; i++){
sum += deals[i].first + deals[i].second;
values.insert(deals[i].first);
values.insert(deals[i].second);
other += *values.begin();
values.erase(*values.begin());
prefix[i+1] = sum - 2 * other;
}
values.clear();
sum = other = 0;
for (int i = (n-1); i > -1; i--){
sum += deals[i].first + deals[i].second;
values.insert(deals[i].first);
values.insert(deals[i].second);
other += *values.begin();
values.erase(*values.begin());
suffix[i] = sum - 2 * other;
}
ll best = prefix[0]+suffix[0];
for (int i = 1; i <= n; i++) best = min(best, prefix[i]+suffix[i]);
ans += best;
}
cout << ans << endl;
}
# | 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... |