# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
531377 | JokerFav | 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 <bits/stdc++.h>
#include <algorithm>
using namespace std;
#define FOR(i, a, b) for(int i = a; i <= b; ++i)
#define FOD(i, a, b) for(int i = a; i >= b; --i)
#define fi first
#define se second
#define pb push_back
#define eb emplace_back
#define ll long long
#define ld long double
#define nmax 400007
void faster()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
}
pair < ll , ll > a[nmax];
int n, m;
ll re[nmax], bl[nmax];
ll sa[nmax], sb[nmax];
int last[nmax], vitri[nmax];
ll dp[nmax];
int main()
{
faster();
//freopen("PointRB.inp","r",stdin);
//freopen("PointRB.out","w",stdout);
cin >> n >> m;
FOR(i, 1, n)
{
cin >> re[i];
a[i] = {re[i], 0};
}
FOR(i, 1, m)
{
cin >> bl[i];
a[n + i] = {bl[i], 1};
}
sort(a + 1,a + 1 + n + m);
sort(re + 1, re + 1 + n);
sort(bl + 1, bl + 1 + m);
int dem = n + m;
FOR(i, 0, 2 * (n + m + 1)) last[i] = vitri[i] = -1;
last[n + m] = 0;
FOR(i, 1, n + m)
{
sa[i] = sa[i - 1] + (a[i].se == 0) * a[i].fi;
sb[i] = sb[i - 1] + (a[i].se == 1) * a[i].fi;
dem += (a[i].se == 0);
dem -= (a[i].se == 1);
if(last[dem] >= 0) vitri[i] = last[dem];
last[dem] = i;
}
dp[0] = 0;
FOR(i, 1, n + m)
{
ll val = 1e10;
if(a[i].se == 0)
{
int id = lower_bound(bl + 1, bl + 1 + m, a[i].fi) - bl;
if(id != m + 1) val = min(val, bl[id] - a[i].fi);
if(id != 1) val = min(val, a[i].fi - bl[id - 1]);
}
else
{
int id = lower_bound(re + 1,re + 1 + n, a[i].fi) - re;
if(id != n + 1) val = min(val, re[id] - a[i].fi);
if(id != 1) val = min(val, a[i].fi - re[id - 1]);
}
dp[i] = dp[i - 1] + val;
if(vitri[i] != -1) dp[i] = min(dp[i], abs(sa[i] - sa[vitri[i]] - sb[i] + sb[vitri[i]]) + dp[vitri[i]]);
}
cout << dp[n + m];
return 0;
}