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>
#include "wiring.h"
#define ll long long
#define mp make_pair
#define pb push_back
using namespace std;
const int maxn = 200100;
vector<pair<int, char> > v;
ll dp[maxn];
int n;
bool valid(int l, int r) {
int max_r = INT_MIN, min_r = INT_MAX;
int max_b = INT_MIN, min_b = INT_MAX;
int rcnt = 0, bcnt = 0;
for(int i=l;i<=r;i++) {
if(v[i].second == 'R') {
max_r = max(max_r, v[i].first);
min_r = min(min_r, v[i].first);
rcnt++;
}
else {
max_b = max(max_b, v[i].first);
min_b = min(min_b, v[i].first);
bcnt++;
}
}
if(bcnt == 0 || rcnt == 0) return false;
return (max_r < min_b) || (max_b < min_r);
}
ll cost(int l, int r) {
int max_r = INT_MIN, min_r = INT_MAX;
int max_b = INT_MIN, min_b = INT_MAX;
ll rcnt = 0LL, bcnt = 0LL;
for(int i=l;i<=r;i++) {
if(v[i].second == 'R') {
max_r = max(max_r, v[i].first);
min_r = min(min_r, v[i].first);
rcnt++;
}
else {
max_b = max(max_b, v[i].first);
min_b = min(min_b, v[i].first);
bcnt++;
}
}
ll sum = 0LL;
if(min_r > max_b) {
// B B B R R
sum = (1LL * min_r - 1LL * max_b) * 1LL * max(bcnt, rcnt);
for(int i=l;i<=r;i++) {
if(v[i].second == 'R') {
sum += v[i].first - min_r;
}
else {
sum += max_b - v[i].first;
}
}
}
else {
// R R R B B
sum = (1LL * min_b - 1LL * max_r) * 1LL * max(bcnt, rcnt);
for(int i=l;i<=r;i++) {
if(v[i].second == 'R') {
sum += max_r - v[i].first;
}
else {
sum += v[i].first - min_b;
}
}
}
return sum;
}
long long min_total_length(std::vector<int> r, std::vector<int> b) {
n = r.size() + b.size();
for(int i:r) {
v.pb(mp(i, 'R'));
}
for(int i:b) {
v.pb(mp(i, 'B'));
}
v.pb(mp(-1, 'A'));
sort(v.begin(), v.end());
dp[0] = 0LL;
for(int i=1;i<=n;i++) {
dp[i] = (1LL << 45);
for(int j=i-1;j>=1;j--) {
if(valid(j, i)) {
dp[i] = min(dp[i], dp[j-1] + cost(j, i));
}
}
}
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... |