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 "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)
{
const auto dnc = [&](const auto &self, int l, int r, int optL, int optR) -> void
{
if (l > r)
return;
int mid = (l + r) >> 1;
ll optVal = inf;
int optIdx = -1;
for (int k = optL; k <= optR; ++k)
{
ll val = cost(k, mid) + dp[k-1];
if (val < optVal)
optVal = val, optIdx = k;
}
dp[mid] = optVal;
self(self, l, mid-1, optL, optIdx);
self(self, mid+1, r, optIdx, optR);
};
dnc(dnc, i, T[i], S[i-1], i-1);
// for (int j = i; j <= T[i]; ++j)
// {
// for (int k = S[i-1]; k < i; ++k)
// {
// dp[j] = min(dp[j], cost(k, j) + dp[k-1]);
// }
// }
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 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... |