#include "wiring.h"
#include <vector>
using namespace std;
long long min_total_length(vector<int> r, vector<int> b) {
int N = r.size() + b.size();
int ridx = 0, bidx = 0;
vector<pair<int, int>> v;
while (ridx < r.size() || bidx < b.size()) {
if (bidx == b.size()) {
v.push_back(make_pair(r[ridx], 0));
ridx++;
} else if (ridx == r.size()) {
v.push_back(make_pair(b[bidx], 1));
bidx++;
} else if (r[ridx] < b[bidx]) {
v.push_back(make_pair(r[ridx], 0));
ridx++;
} else {
v.push_back(make_pair(b[bidx], 1));
bidx++;
}
}
vector<long long> dp(N, (long long)1e18);
for (int idx = 0; idx < N; ) {
int clb = idx, crb = idx;
while (crb < N && v[crb].second == v[clb].second) {
crb++;
}
idx = crb;
crb--;
if (clb == 0) {
continue;
}
int prb = clb - 1, plb = prb;
while (plb >= 0 && v[plb].second == v[prb].second) {
plb--;
}
plb++;
for (int c = clb; c <= crb; c++) {
int psz = prb - plb + 1, csz = c - clb + 1;
long long sum = 0;
if (psz <= csz) {
for (int i = 0; i < psz; i++) {
sum += v[clb + i].first - v[plb + i].first;
}
for (int i = psz; i < csz; i++) {
sum += v[clb + i].first - v[prb].first;
}
} else {
for (int i = 0; i < csz; i++) {
sum += v[clb + i].first - v[plb + i].first;
}
for (int i = csz; i < psz; i++) {
sum += v[clb].first - v[plb + i].first;
}
}
for (int i = 0; i < max(psz, csz); i++) {
int p = plb + i;
long long cur = (plb == 0 ? 0 : min(dp[p - 1], dp[p]));
dp[c] = min(dp[c], cur + sum);
if (i < max(psz, csz)) {
sum += v[plb + i].first;
if (psz - i > csz) {
sum -= v[clb].first;
} else {
sum -= v[prb].first;
}
}
if (plb == 0) {
break;
}
}
}
}
return dp[N - 1];
}
| # | 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... |