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 int long long
using namespace std;
int n,a[1000000],q,st;
void solve(){
int ans=0;
auto* it=lower_bound(a+1,a+n+1,st);
int pos=it-a;
if(pos>0 && abs(st-a[pos-1])<=abs(a[pos]-st)){
pos--;
}
ans+=abs(st-a[pos]);
int x=pos-1;
int y=pos+1;
//cout<<pos<<endl;
while(1<=x || y<=n){
if(abs(a[x]-a[pos])<=abs(a[y]-a[pos])){
//cout<<"! goleft"<<endl;
int l=1;
int r=x;
while(l<=r){
int mid=(l+r)/2;
if(abs(a[pos]-a[mid])<=abs(a[y]-a[pos])){
r=mid-1;
}
else{
l=mid+1;
}
}
r++;
if(abs(a[r]-a[pos])<=abs(a[pos]-a[y])){
ans+=abs(a[r]-a[pos]);
x=r-1;
pos=r;
}
}
else{
//cout<<"! goright"<<endl;
int l=y;
int r=n;
while(l<=r){
int mid=(l+r)/2;
if(abs(a[mid]-a[pos])<abs(a[x]-a[pos])){
l=mid+1;
}
else{
r=mid-1;
}
}
l--;
if(abs(a[l]-a[pos])<abs(a[pos]-a[x])){
ans+=abs(a[pos]-a[l]);
pos=l;
y=l+1;
}
}
//cout<<x<<' '<<y<<' '<<pos<<endl;
}
cout<<ans<<endl;
}
signed main(){
cin>>n;
for(int i=1;n>=i;i++){
cin>>a[i];
}
a[0]=a[n+1]=100000000000000000;
cin>>q;
while(q--){
cin>>st;
solve();
}
}
# | 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... |