Submission #600078

#TimeUsernameProblemLanguageResultExecution timeMemory
600078DanShadersWiring (IOI17_wiring)C++17
100 / 100
102 ms16312 KiB
//grader.cpp
#include "wiring.h"
#include <bits/stdc++.h>
using namespace std;

#define x first
#define y second
#define all(x) begin(x), end(x)
#define sz(x) ((int) (x).size())
using ll = long long;
using ld = long double;

const int N = 2e5 + 10;
const ll INF = 0x3f3f3f3f3f3f3f3f;

ll dp[N], pref[N], fend[N];

ll min_total_length(vector<int> r, vector<int> b) {
#define int ll
	vector<pair<int, int>> a;
	for (int u : r) {
		a.push_back({u, 0});
	}
	for (int u : b) {
		a.push_back({u, 1});
	}
	sort(all(a));

	int k = sz(a);
	fend[k - 1] = k;
	for (int i = k - 1; i--; ) {
		if (a[i].y != a[i + 1].y) {
			fend[i] = i + 1;
		} else {
			fend[i] = fend[i + 1];
		}
	}
	for (int i = 0; i < k; ++i) {
		pref[i + 1] = pref[i] + a[i].x;
	}

	fill(all(dp), +INF);
	dp[0] = 0;
	pair<int, int> lst = {0, 0};

	multiset<ll> neg, pos;

	for (int i = 0; i < k; ++i) {
		if (i && a[i].y != a[i - 1].y) {
			lst = {lst.y, i};
		}
		if (lst.y) {
			if (lst.y == i) {
				neg.clear();
				pos.clear();
				for (int j = lst.x; j <= lst.y; ++j) {
					ll balance = i + j - 2 * lst.y + 1;
					if (balance < 0) {
						neg.insert(-(pref[lst.y] - pref[j]) + dp[j] - a[lst.y].x * (j - 2 * lst.y + 1));
					} else {
						pos.insert(-(pref[lst.y] - pref[j]) + dp[j] - a[lst.y - 1].x * (j - 2 * lst.y + 1));
					}
				}
			} else {
				// i + j - 2 * lst.y + 1 == 0
				int j = 2 * lst.y - 1 - i;
				if (j >= lst.x && j <= lst.y) {
					neg.erase(neg.find(-(pref[lst.y] - pref[j]) + dp[j] - a[lst.y].x * (j - 2 * lst.y + 1)));
					pos.insert(-(pref[lst.y] - pref[j]) + dp[j] - a[lst.y - 1].x * (j - 2 * lst.y + 1));
				}
			}
			// for (int j = lst.x; j <= lst.y; ++j) {
			// 	ll balance = i + j - 2 * lst.y + 1, ans = 0;
			// 	if (balance < 0) {
			// 		ans -= a[lst.y].x * balance;
			// 	} else {
			// 		ans -= a[lst.y - 1].x * balance;
			// 	}
			// 	ans -= pref[lst.y] - pref[j];
			// 	if (dp[i + 1] > ans + dp[j]) {
			// 		dp[i + 1] = ans + dp[j];
			// 	}
			// }
			if (sz(neg)) {
				dp[i + 1] = min(dp[i + 1], *neg.begin() - i * a[lst.y].x);
			}
			if (sz(pos)) {
				dp[i + 1] = min(dp[i + 1], *pos.begin() - i * a[lst.y - 1].x);
			}
			dp[i + 1] += pref[i + 1] - pref[lst.y];
		}
	}
	// for (int i = 0; i <= k; ++i) {
	// 	cout << dp[i] << " ";
	// }
	// cout << endl;
	return dp[k];
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...