/* Author : Mychecksdead */
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define MOD (1000000000+7)
#define MOD1 (998244353)
#define pb push_back
#define all(x) x.begin(), x.end()
#define en cout << '\n'
#define ff first
#define ss second
#define pii pair<int,int>
#define vi vector<int>
const int N = 1e6+100, M = 1e5+10, K = 52, MX = 30;
int n, q;
ll a[N];
void solve(){
cin >> n;
for(int i = 1; i <= n; ++i){
cin >> a[i];
}
cin >> q;
for(int i = 1; i <= q; ++i){
ll s = 0; cin >> s;
ll ans = 0;
int pos = lower_bound(a+1, a+1+n, s) - a;
if(pos > n){
cout << s - a[1] << '\n';
continue;
}
if(pos == 1){
cout << a[n] - s << '\n';
continue;
}
int cur, l = 0, r = 0;
if(s - a[pos - 1] <= a[pos] - s){
l = pos - 1;
r = pos - 1;
ans += s - a[pos - 1];
}else{
l = pos, r = pos;
ans += a[pos] - s;
}
cur = l;
while(l != 1 || r != n){
if(l == 1){
ans += a[n] - a[cur];
break;
}
if(r == n){
ans += a[cur] - a[1];
break;
}
bool flag = 0, flg = 0;
if(cur == l){
int L = r, R = n, go = r;
while(L <= R){
int m = L+R>>1;
if(a[m] - a[cur] < a[cur] - a[cur - 1]){
go = m;
L = m+1;
}else{
R = m - 1;
}
}
if(go == r){
flag = 1;
}else{
ans += a[go] - a[cur];
cur = go;
r = cur;
flg = 1;
}
}
if((cur == r || flag) && !flg){
int L = 1, R = l, go = l;
while(L <= R){
int m = L+R>>1;
if(a[cur] - a[m] <= a[cur + 1] - a[cur]){
go = m;
R = m-1;
}else{
L = m + 1;
}
}
assert(l != go);
ans += a[cur] - a[go];
cur = go;
l = go;
}
}
cout << ans << '\n';
}
}
int main(){
cin.tie(0); ios::sync_with_stdio(0);
int tt = 1, aa;
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
while(tt--){
solve();
}
cerr<<"time taken : "<<(float)clock()/CLOCKS_PER_SEC<<" seconds\n";
return 0;
}
# | 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... |