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 pii = pair<int, int>;
using ll = long long;
#define ff first
#define ss second
int K, N, cnt;
ll pfx[100005], sfx[100005], cost;
pii P[100005];
vector<int> x;
void f(ll *f) {
priority_queue<pii, vector<pii>, greater<pii> > pq;
for (int i = 1; i <= N; ++i) x.push_back(P[i].ff);
sort(x.begin(), x.end());
x.erase(unique(x.begin(), x.end()), x.end());
int s = 0;
for (int i = 1, j = 0; i <= N; ++i) {
f[i] = f[i - 1] + 2 * max({0, P[i].ff - x[j], x[j] - P[i].ss});
pq.emplace(P[i].ff, 2);
pq.emplace(P[i].ss, 2);
s -= 2;
while (pq.size() && pq.top().ff <= x[j]) {
s += pq.top().ss;
pq.pop();
}
while (s < 0) {
f[i] += 1ll * s * (x[j + 1] - x[j]);
j++;
while (pq.size() && pq.top().ff <= x[j]) {
s += pq.top().ss;
pq.pop();
}
}
}
}
int main() {
ios_base::sync_with_stdio(0), cin.tie(0);
cin >> K >> N;
for (int i = 0; i < N; ++i) {
char a, b; int c, d; cin >> a >> c >> b >> d;
cost += abs(c - d);
if (a != b) {
cost++;
if (c > d) swap(c, d);
P[++cnt] = {c, d};
}
}
N = cnt;
sort(P + 1, P + N + 1, [&](pii a, pii b) { return a.ff + a.ss < b.ff + b.ss; });
f(pfx);
if (K < 2) return !printf("%lld\n",pfx[N] + cost);
reverse(P + 1, P + N + 1);
for (int i = 1; i <= N; ++i) {
P[i].ff = 1e9 - P[i].ff;
P[i].ss = 1e9 - P[i].ss;
swap(P[i].ff, P[i].ss);
}
f(sfx);
ll mn = pfx[N];
for (int i = 1; i < N; ++i) mn = min(mn, pfx[i] + sfx[N - i]);
cout << mn + cost;
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... |