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 "wiring.h"
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
#define F first
#define S second
#define INF 1e18
#define all(v) (v).begin(),(v).end()
#define rall(v) (v).rbegin(),(v).rend()
#define pii pair<int,int>
#define pll pair<ll,ll>
#define OK cout<<"Ok"<<endl;
#define MOD (ll)(1e9+7)
long long min_total_length(vector<int> a, vector<int> b) {
set<int>st;
set<int>st2;
if(a.size()>b.size()) swap(a,b);
for(int v:a){
st2.insert(v);
}
int n=a.size(),m=b.size();
if(max(n,m)<=200){
ll ans=INF;
for(int i=0;i+n-1<b.size();i++){
ll res=0;
for(int j=0;j<i;j++){
int x=b[j];
auto l=st2.upper_bound(x-1);
auto r=st2.lower_bound(x);
if(l!=st2.begin()&&r!=st2.end()){
l--;
int y=*l,z=*r;
if(abs(y-x)<abs(z-x)){
res+=abs(y-x);
}
else{
res+=abs(z-x);
}
}
else if(l!=st2.begin()){
l--;
int y=*l;
res+=abs(y-x);
}
else if(r!=st2.end()){
int y=*r;
res+=abs(y-x);
}
}
int idx=i;
for(int j=0;j<n;j++){
res+=abs(a[j]-b[idx]);
idx++;
}
while(idx<m){
int x=b[idx];
auto l=st2.upper_bound(x-1);
auto r=st2.lower_bound(x);
if(l!=st2.begin()&&r!=st2.end()){
l--;
int y=*l,z=*r;
if(abs(y-x)<abs(z-x)){
res+=abs(y-x);
}
else{
res+=abs(z-x);
}
}
else if(l!=st2.begin()){
l--;
int y=*l;
res+=abs(y-x);
}
else if(r!=st2.end()){
int y=*r;
res+=abs(y-x);
}
idx++;
}
ans=min(ans,res);
}
return ans;
}
for(int v:b){
st.insert(v);
}
ll ans=0;
for(int x:a){
auto l=st.upper_bound(x-1);
auto r=st.lower_bound(x);
if(l!=st.begin()&&r!=st.end()){
l--;
int y=*l,z=*r;
if(abs(y-x)<abs(z-x)){
ans+=abs(y-x);
st.erase(l);
}
else{
ans+=abs(z-x);
st.erase(r);
}
}
else if(l!=st.begin()){
l--;
int y=*l;
ans+=abs(y-x);
st.erase(l);
}
else if(r!=st.end()){
int y=*r;
ans+=abs(y-x);
st.erase(r);
}
}
for(int x:st){
auto l=st2.upper_bound(x-1);
auto r=st2.lower_bound(x);
if(l!=st2.begin()&&r!=st2.end()){
l--;
int y=*l,z=*r;
if(abs(y-x)<abs(z-x)){
ans+=abs(y-x);
}
else{
ans+=abs(z-x);
}
}
else if(l!=st2.begin()){
l--;
int y=*l;
ans+=abs(y-x);
}
else if(r!=st2.end()){
int y=*r;
ans+=abs(y-x);
}
}
return ans;
}
Compilation message (stderr)
wiring.cpp: In function 'long long int min_total_length(std::vector<int>, std::vector<int>)':
wiring.cpp:25:26: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
25 | for(int i=0;i+n-1<b.size();i++){
| ~~~~~^~~~~~~~~
# | 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... |