Submission #595956

#TimeUsernameProblemLanguageResultExecution timeMemory
595956Drew_Wiring (IOI17_wiring)C++17
100 / 100
87 ms10188 KiB
#include "wiring.h"
#include <bits/stdc++.h>
using namespace std;

#define f1 first
#define s2 second
#define pb push_back

using ii = pair<int, int>;
using ll = long long;

const int MAX = 2e5 + 69;
const int inf = 1e9 + 69;
const ll inf_ = (ll)1e18 + 69;

ll dp[MAX], pfx[MAX];
int S[MAX], T[MAX]; // start and end of components.

ll min_total_length(vector<int> R, vector<int> B) 
{
	fill(dp, dp + MAX, inf_);

	vector<ii> v = { {-1, -1}, {inf, inf} };
	for (int x : R)
		v.pb({x, 0});
	for (int x : B)
		v.pb({x, 1});
	sort(v.begin(), v.end());

	// divide r and b into contigious segments of same color
	// point frm a segment will only connect to its neighbouring segments.

	int N = (int)R.size() + (int)B.size();

	for (int i = 1; i <= N; ++i)
		pfx[i] = pfx[i-1] + v[i].f1;

	for (int i = 1; i <= N; ++i)
	{
		if (v[i].s2 == v[i-1].s2) S[i] = S[i-1];
		else S[i] = i;
	}

	for (int i = N; i >= 1; --i)
	{
		if (v[i].s2 == v[i+1].s2) T[i] = T[i+1];
		else T[i] = i;
	}

	const auto cost = [&](int l, int r) -> ll
	{
		int m = S[r];
		assert(T[l] + 1 == m);

		int a = m-l, b = r-m+1;
		ll res = (pfx[r] - pfx[m-1]) - (pfx[m-1] - pfx[l-1]);

		if (a < b) res -= 1ll * (b-a) * v[m-1].f1;
		else res += 1ll * (a-b) * v[m].f1;

		return res;
	};

	dp[0] = 0;
	for (int i = T[1] + 1; i <= N; i = T[i] + 1)
	{
		if (i == T[1] + 1)
		{
			for (int j = i; j <= T[i]; ++j)
				dp[j] = cost(1, j) + dp[0];
		}
		else
		{
			for (int j = i; j <= T[i]; ++j)
			{
				int l = S[i-1], r = i-1;
				while (l < r)
				{
					int mid = (l + r + 1) >> 1;
					if (cost(mid, j) + dp[mid-1] > cost(mid-1, j) + dp[mid-2]) r = mid - 1; // gradient is inreasing
					else l = mid;
				}
				dp[j] = cost(l, j) + dp[l-1];

				// for (int k = S[i-1]; k < i; ++k)
				// {
				// 	dp[j] = min(dp[j], cost(k, j) + dp[k-1]);
				// 	cerr << cost(k, j) + dp[k-1] << ", ";
				// }
				// cerr << '\n';
			}
		}

		for (int j = T[i]; j >= S[i-1]; --j)
			dp[j-1] = min(dp[j-1], dp[j]);
	}

	// for (int i = 1; i <= N; ++i)
	// 	cerr << i << ": " << dp[i] << '\n';

	return dp[N];
}
#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...