#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
using namespace std;
using namespace __gnu_pbds;
#define fi first
#define se second
#define pb push_back
#define int long long
#define sz(a) (int)a.size()
#define all(a) begin(a),end(a)
#define uid(a, b) uniform_int_distribution<int>(a, b)(rng)
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
using ll = long long;
using vi = vector<int>;
using ar2 = array<int,2>;
using ar3 = array<int,3>;
const int mxN = (int)2e5+10;
const int INF = (int)1e9;
const ll LINF = (ll)2e18;
const int mxLg = 20;
int n, q;
int x[mxN], y[mxN];
int jmp[mxLg][mxN];
int32_t main(){
ios_base::sync_with_stdio(false); cin.tie(0);
cin >> n; stack<int> S;
for(int i = 1; i <= n; i++) cin >> x[i];
for(int i = 2; i <= n; i++)
y[i] = 2*x[i]-x[i-1];
for(int i = 2; i <= n; i++){
while(sz(S) and y[S.top()] <= y[i]) S.pop();
if(sz(S)) jmp[0][i]=S.top();
S.push(i);
}
for(int j = 1; j < mxLg; j++)
for(int i = 1; i <= n; i++)
jmp[j][i] = jmp[j-1][jmp[j-1][i]];
cin >> q;
while(q--){
int s, ans=0, l=1, r=n; cin >> s;
int pos = upper_bound(x+1,x+n+1,s)-x-1;
if(pos>=n) l=r=n,ans+=abs(x[n]-s);
else{
if(abs(x[pos]-s) > abs(x[pos+1]-s)) pos++;
ans+=abs(x[pos]-s),l=r=pos;
}
while(1){
if(l==1 or r==n){
if(l!=1 or r!=n) ans+=x[n]-x[1];
break;
}
if(y[l] <= x[r+1]){
while(l>=2 and y[l]<=x[r+1]) l--;
//for(int j = mxLg-1; j>=0; j--)
// if(jmp[j][l] and y[jmp[j][l]]<=x[r+1]) l=jmp[j][l];
//l=jmp[0][l]+1;
}
else{
while(r<n and y[l]>x[r+1]) r++;
//r = lower_bound(x+r+2,x+n+1,y[l])-x;
//r = min(r,n);
}
ans+=x[r]-x[l];
}
cout << ans << "\n";
}
}
# | 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... |