#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define re exit(0);
const int LOG = 18;
int n,x[200009];
int sparse1[200009][LOG + 1],sparse2[200009][LOG + 1];
ll calc(int l,int r,int pos) {
if (l == 0) return x[n] - pos;
if (r == n + 1) return pos - x[1];
int left = pos - x[l],right = x[r] - pos;
if (left <= right) {
//vi tri cach xa nhat ma
//x_i - x_i-1 <= x_r - x_i
//2*x_i - x_i-1 <= x_r
if (l == 1 || 2*x[l] - x[l - 1] > x[r]) return left + calc(l - 1,r,x[l]);
int temp = l;
for (int i = 0;i <= LOG;i++) if (temp - (1 << i) >= 2 && sparse1[temp - (1 << i)][i] <= x[r]) {
temp -= (1 << i);
}
return pos - x[temp - 1] + calc(temp - 2,r,x[temp - 1]);
} else {
//vi tri cach xa nhat ma
//x_i+1 - x_i < x_i - x_l
//2*x_i - x_i+1 > x_l
if (r == n || 2*x[r] - x[r + 1] <= x[l]) return right + calc(l,r + 1,x[r]);
int temp = r;
for (int i = 0;i <= LOG;i++) if (temp + (1 << i) < n && sparse2[temp + 1][i] > x[l]) {
temp += (1 << i);
}
return x[temp + 1] - pos + calc(l,temp + 2,x[temp + 1]);
}
}
int main() {
ios_base::sync_with_stdio(0);cin.tie(nullptr);
cin >> n;
for (int i = 1;i <= n;i++) {
cin >> x[i];
}
for (int i = 1;i <= n;i++) {
sparse1[i][0] = 2 * x[i] - x[i - 1];
sparse2[i][0] = 2 * x[i] - x[i + 1];
}
for (int j = 1;j <= LOG;j++) {
for (int i = 1;i + (1 << j) - 1 <= n;i++) {
sparse1[i][j] = max(sparse1[i][j - 1],sparse1[i + (1 << (j - 1))][j - 1]);
sparse2[i][j] = min(sparse2[i][j - 1],sparse2[i + (1 << (j - 1))][j - 1]);
}
}
int q;cin >> q;
while (q--) {
int pos;cin >> pos;
int l = upper_bound(x + 1,x + 1 + n,pos) - x - 1;
int r = upper_bound(x + 1,x + 1 + n,pos) - x;
cout << calc(l,r,pos) << '\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... |