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;
#define ll long long
#define pb push_back
#define sz size()
#define pii pair <ll, ll>
#define ff first
#define ss second
const int N = 1e5 + 5;
ll jogap, a[N], b[N], p[N], q[N];
int n, k;
ll sum, sum1;
char oy[N], of[N];
vector <pii> v;
multiset <ll> cep, sag;
bool cmp (pii x, pii y) {
return x.ff + x.ss < y.ff + y.ss;
}
void gosh (ll x) {
if (cep.empty()) {
cep.insert (x);
sum += x;
}
else if ((int)cep.sz <= (int)sag.sz) {
ll val = *sag.begin();
if (x <= val) {
cep.insert (x);
sum += x;
}
else {
cep.insert (val);
sum1 -= val;
sag.erase (sag.begin());
sum1 += x;
sag.insert (x);
}
}
else {
auto tr = cep.end();
tr--;
ll val = *tr;
if (val <= x) {
sag.insert(x);
sum1 += x;
}
else {// val > x
sag.insert (val);
sum1 += val;
sum -= val;
cep.erase (tr);
cep.insert (x);
sum += x;
}
}
}
ll query () {
auto tr = cep.end();
tr--;
ll a1 = (ll)cep.sz, a2 = (ll)sag.sz, git = *tr;
return (a1 * git - sum) + (sum1 - a2 * git);
}
int main () {
// ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
// freopen ("input.txt", "r", stdin);
cin >> k >> n;
for (int i = 1; i <= n; ++i) {
cin >> oy[i] >> a[i] >> of[i] >> b[i];
}
ll goshmaly = 0;
jogap = 2e18;
for (int i = 1; i <= n; ++i) {
if (oy[i] == of[i]) {
goshmaly += abs (a[i] - b[i]);
}
else {
v.pb ({a[i], b[i]});
goshmaly++;
}
}
if (!v.empty()) {
sort (v.begin(), v.end(), cmp);
// for (auto i : v) {
// cout << i.ff << " " << i.ss << "\n";
// }
// return 0;
for (int i = 0; i < (int)v.sz; ++i) {
gosh (v[i].ff);
gosh (v[i].ss);
p[i] = query();
}
cep.clear();
sag.clear();
sum = sum1 = 0;
for (int i = (int)v.sz - 1; i >= 0; i--) {
gosh (v[i].ff);
// cout << i << "->" << q[i] << "\n";
gosh (v[i].ss);
q[i] = query();
}
// return cout << "men", 0;
assert (q[0] == p[(int)v.sz - 1]);
jogap = q[0];
if (k > 1) {
for (int i = 0; i < (int)v.sz - 1; ++i) {
jogap = min (jogap, p[i] + q[i + 1]);
}
}
}
if (jogap == 2e18) jogap = 0;
cout << jogap + goshmaly;
}
# | 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... |