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>
using namespace std;
using ll=long long;
using pp=pair<int,int>;
#define eb emplace_back
#define all(x) (x).begin(), (x).end()
#define sz(x) ((int)((x).size()))
#define rep(i,n) for(int i=0; i<(n); ++i)
#define rrep(i,n) for(int i=1; i<=(n); ++i)
#define x first
#define y second
const int maxn = int(2e5) + 10;
ll dp[maxn];
const ll inf = 1ll<<60;
int n;
vector<pp> a;
int lev[maxn];
int levbef[maxn*2];
int bef[maxn];
int bx[maxn];
int nx[maxn];
ll pd[maxn];
void pre() {
rep(i, n) {
if (i) pd[i] = pd[i-1];
if (a[i].y) pd[i] += a[i].x;
else pd[i] -= a[i].x;
}
int l = n;
rep(i, n) {
if (a[i].y) ++l; else --l;
lev[i] = l;
levbef[l] = -2;
}
levbef[n] = -1;
int last[2] = {-1, -1};
rep(i, n) {
int c = a[i].y, d = c^1;
bef[i] = last[c];
bx[i] = last[d];
last[c] = i;
}
last[0] = last[1] = -1;
for(int i=n-1; 0<=i; --i) {
int c = a[i].y, d = c^1;
nx[i] = last[d];
last[c] = i;
}
}
ll min_total_length(vector<int> vr, vector<int> vb) {
a.clear();
for(int x:vr) a.eb(x, 0);
for(int x:vb) a.eb(x, 1);
sort(all(a));
n = sz(a);
pre();
fill(dp, dp+n, inf);
{
int p = nx[0];
for(int j=0; a[j].y == a[0].y; ++j) {
int cnt = j+1;
ll ps = abs(pd[j]);
dp[j] = a[p].x * 1ll * cnt - ps;
}
}
rep(i, n) {
{
int k = levbef[lev[i]];
if (k != -2) {
ll df = abs(pd[i] - (k >= 0 ? pd[k] : 0ll));
ll tmp = (k >= 0 ? dp[k] : 0ll) + df;
dp[i] = min(dp[i], tmp);
}
levbef[lev[i]] = i;
}
if (nx[i] != -1) {
ll tmp = dp[i-1] + abs(a[nx[i]].x-a[i].x);
dp[i] = min(dp[i], tmp);
}
if (bx[i] != -1) {
ll tmp = ((bx[i] == i-1) ? dp[i-2] : dp[i-1]) + abs(a[bx[i]].x-a[i].x);
dp[i] = min(dp[i], tmp);
}
if (i+1 < n && nx[i+1] != -1) {
int j = nx[i+1];
ll ps = abs(pd[j-1]-pd[i]);
int cnt = j-i-1;
ll tmp = dp[i] + a[j].x * 1ll * cnt - ps;
dp[j] = min(dp[j], tmp);
}
}
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... |