제출 #765616

#제출 시각아이디문제언어결과실행 시간메모리
765616NK_Coin Collecting (JOI19_ho_t4)C++17
100 / 100
42 ms7368 KiB
// 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);

		// cout << abs((r + 1) - y) + abs((c + 1) - x) << " " << r << " " << c << endl;

		A[r][c]++;
	}

	// for(int r = 0; r < 2; r++) {
	// 	for(int c = 0; c < N; c++) cout << A[r][c] << " ";
	// 	cout << nl;
	// }

	// cout << ans << nl;

	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();
				// cout << pr << ", " << pc << " <->  " << r << ", " << i << endl;
				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();
				// cout << pr << ", " << pc << " <->  " << r << ", " << i << endl;
				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();
				// cout << pr << ", " << pc << " <->  " << r << ", " << i << endl;
				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();
				// cout << pr << ", " << pc << " <->  " << r << ", " << i << endl;
				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 timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...