# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
142814 | babo | 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 inf 2000000000
#define all(x) (x).begin(),(x).end()
#define L long long
using namespace std;
struct S{
L loc,det,chk,lev;
}a[200020];
set<L>st[200020];
L n,m;
L min_total_length(vector<int>r, vector<int>b){
n=r.size();
m=b.size();
L i,ret=0;
for(i=0;i<n;i++)
{
a[i]=(S){r[i],1,0};
}
for(i=n;i<n+m;i++)
{
a[i]=(S){b[i-n],2,0};
}
sort(a,a+n+m,[](S a,S b){
return a.loc<b.loc;
});
L lev=100010;
for(i=0;i<n+m;i++)
{
a[i].lev=lev;
st[lev].insert(i);
if(a[i].det==1&&a[i+1].det==1) lev++;
if(a[i].det==2&&a[i+1].det==2) lev--;
//printf("%lld %lld\n",a[i].det,a[i].loc);
}
for(i=0;i<n+m;i++)
{
if(a[i].chk) continue;
set<L>::iterator it=st[a[i].lev].upper_bound(i);
if(it!=st[a[i].lev].end())
{
//printf("match %lld %lld\n",i,*it);
a[i].chk=1;
a[*it].chk=1;
ret+=a[*it].loc-a[i].loc;
st[a[i].lev].erase(it);
st[a[i].lev].erase(i);
}
else
{
L mi=inf;
vector<int>::iterator it;
if(a[i].det==1)
{
it=lower_bound(all(b),a[i].loc);
if(it!=b.end())
mi=min(mi,*it-a[i].loc);
it=upper_bound(all(b),a[i].loc);
if(it!=b.begin())
mi=min(mi,a[i].loc-*(prev(it)));
}
else
{
it=lower_bound(all(r),a[i].loc);
if(it!=r.end())
mi=min(mi,*it-a[i].loc);
it=upper_bound(all(r),a[i].loc);
if(it!=r.begin())
mi=min(mi,a[i].loc-*(prev(it)));
}
ret+=mi;
}
}
return ret;
}
#include <cassert>
#include <cstdio>
using namespace std;
int main() {
int n, m;
assert(2 == scanf("%d %d", &n, &m));
vector<int> r(n), b(m);
for(int i = 0; i < n; i++)
assert(1 == scanf("%d", &r[i]));
for(int i = 0; i < m; i++)
assert(1 == scanf("%d", &b[i]));
long long res = min_total_length(r, b);
printf("%lld\n", res);
return 0;
}