# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
931712 | Aiperiii | 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>
//#include "wiring.h"
#define ll long long
#define ff first
#define ss second
#define all(x) x.begin(),x.end()
#define pb push_back
using namespace std;
const int N=2e5+5;
ll dp[N],pr[N];
long long min_total_length(vector<int> r,vector<int> b) {
vector <pair <ll,ll> > v;
v.pb({0,-1});
for(int i=0;i<r.size();i++)v.pb({r[i],-1});
for(int i=0;i<b.size();i++)v.pb({b[i],1});
sort(all(v));
int cnt=0;
map <int,int> pos;
for(int i=1;i<v.size();i++){
pr[i]=pr[i-1]+v[i].ff*v[i].ss;
cnt+=v[i].ss;
ll x=1e18;
if(v[i].ss==-1){
auto it=upper_bound(all(b),v[i].ff);
if(it!=b.end())x=min(x,*it-v[i].ff);
if(it!=b.begin()){
it--;
x=min(x,abs(*it-v[i].ff));
}
}
else{
auto it=upper_bound(all(r),v[i].ff);
if(it!=r.end())x=min(x,*it-v[i].ff);
if(it!=r.begin()){
it--;
x=min(x,abs(*it-v[i].ff));
}
}
dp[i]=dp[i-1]+x;
if(cnt==0 or pos[cnt]>0)dp[i]=min(dp[i],dp[pos[cnt]]+abs(pr[i]-pr[pos[cnt]]));
pos[cnt]=i;
}
return dp[v.size()-1];
}
signed main(){
ios_base::sync_with_stdio();
cin.tie(0);cout.tie(0);
int n,m;
cin>>n>>m;
vector <int> a(n),b(m);
for(int i=0;i<n;i++)cin>>a[i];
for(int i=0;i<m;i++)cin>>b[i];
cout<<min_total_length(a,b);
}
/*
1 2 3 7
0 4 5 9 10
0,0 0,1 1,0, 2,0 3,0 4,1 5,1 7,0 9,1 10,1
0 0 -1 -3
0 1 1 3
*/