# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
595820 | Drew_ | Wiring (IOI17_wiring) | C++17 | 0 ms | 0 KiB |
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)
{
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]);
}
}
}
return dp[N];
}
int main() {
int n, m;
assert(2 == scanf("%d %d", &n, &m));
vector<int> r(n), b(m);
for(int i = 0; i < n; i++)
assert(1 == scanf("%d", &r[i]));
for(int i = 0; i < m; i++)
assert(1 == scanf("%d", &b[i]));
long long res = min_total_length(r, b);
printf("%lld\n", res);
return 0;
}