This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
// Success consists of going from failure to failure without loss of enthusiasm
#include <bits/stdc++.h>
using namespace std;
#define nl '\n'
#define sz(x) int(x.size())
using ll = long long;
template<class T> using V = vector<T>;
int main() {
cin.tie(0)->sync_with_stdio(0);
int N; cin >> N;
V<V<int>> A(2, V<int>(N, 0));
ll ans = 0;
for(int t = 0; t < 2*N; t++) {
int x, y; cin >> x >> y;
int r = (y >= 2 ? 1 : 0);
int c = min(max(1, x), N) - 1;
ans += abs((r + 1) - y);
ans += abs((c + 1) - x);
A[r][c]++;
}
V<queue<array<int, 2>>> E(2), F(2); // EMPTY or FILLED
for(int i = 0; i < N; i++) {
for(int r = 0; r < 2; r++) {
if (A[r][i] > 1) while(A[r][i] > 1 && sz(E[r])) {
auto [pr, pc] = E[r].front(); E[r].pop();
ans += abs(r - pr) + abs(pc - i);
--A[r][i];
}
if (A[r][i] < 1) while(A[r][i] < 1 && sz(F[r])) {
auto [pr, pc] = F[r].front(); F[r].pop();
ans += abs(r - pr) + abs(pc - i);
A[r][i]++;
}
}
for(int r = 0; r < 2; r++) {
if (A[r][i] > 1) while(A[r][i] > 1 && sz(E[r^1])) {
auto [pr, pc] = E[r^1].front(); E[r^1].pop();
ans += abs(r - pr) + abs(pc - i);
--A[r][i];
}
if (A[r][i] < 1) while(A[r][i] < 1 && sz(F[r^1])) {
auto [pr, pc] = F[r^1].front(); F[r^1].pop();
ans += abs(r - pr) + abs(pc - i);
A[r][i]++;
}
for(int t = 0; t < abs(1 - A[r][i]); t++) {
if (A[r][i] < 1) E[r].push({r, i});
else F[r].push({r, i});
}
}
}
cout << ans << nl;
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... |