# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
851332 | ntkphong | Wiring (IOI17_wiring) | C++14 | 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 <bits/stdc++.h>
#define int long long
using namespace std;
const int INF = 1e18;
const int mxN = 2e5 + 10;
int dp[mxN][2];
long long min_total_length(vector<int> r, vector<int> b) {
int n = r.size() + b.size();
vector<pair<int, int>> arr(n + 5);
vector<int> prefix(n + 1, 0);
vector<int> L, R;
for(int i = 0; i < r.size(); i ++) arr[i + 1] = {r[i], 0};
for(int i = 0; i < b.size(); i ++) arr[r.size() + i + 1] = {b[i], 1};
sort(arr.begin() + 1, arr.begin() + n + 1);
for(int i = 1; i <= n; i ++)
prefix[i] = prefix[i - 1] + arr[i].first;
auto get = [&](int l, int r) {
return prefix[r] - prefix[l - 1];
};
for(int i = 1, j = 1; i <= n; i = j + 1) {
for(j = i; j + 1 <= n && arr[j + 1].second == arr[i].second; ) j ++ ;
L.push_back(i);
R.push_back(j);
}
arr[0] = {- INF, 0};
arr[n + 1] = {INF, 0};
for(int i = 1; i <= n; i ++) {
dp[i][0] = dp[i][1] = INF;
}
for(int i = 0; i < L.size(); i ++) {
for(int j = L[i]; j <= R[i]; j ++) {
if(j == L[i]) {
dp[j][0] = min({dp[j][0],
dp[j - 1][0] + arr[j].first - arr[L[i] - 1].first,
dp[j - 1][1] + arr[j].first - arr[L[i] - 1].first});
} else
dp[j][0] = min(dp[j][0], dp[j - 1][0] + arr[j].first - arr[L[i] - 1].first);
dp[j][1] = min({dp[j][1],
dp[j - 1][0] + arr[R[i] + 1].first - arr[j].first,
dp[j - 1][1] + arr[R[i] + 1].first - arr[j].first});
}
if(i + 1 < L.size()) {
for(int j = L[i]; j <= R[i]; j ++) {
int k = R[i] - j + 1;
if(R[i + 1] - L[i + 1] + 1 < k) continue ;
dp[R[i] + k][0] = min({dp[R[i] + k][0],
dp[j - 1][0] + get(R[i] + 1, R[i] + k) - get(j, R[i]),
dp[j - 1][1] + get(R[i] + 1, R[i] + k) - get(j, R[i])});
}
}
}
return dp[n][0];
}