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>
using namespace std;
#define int long long
#define f first
#define s second
const int N = 2e5 + 69;
const int inf = 1e15;
const int K = 18;
vector<vector<int>> levo(N, vector<int>(K, inf)), desno(N, vector<int>(K, -inf));
int x[N], n, q;
signed main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int tt = 1;
//cin >> tt;
while (tt--) {
x[0] = -inf;
cin >> n;
for (int i = 1;i <= n;i++)
cin >> x[i];
x[n + 1] = inf;
for (int i = 1;i <= n;i++)
desno[i][0] = 2 * x[i] - x[i + 1];
for (int i = 1;i <= n;i++)
levo[i][0] = 2 * x[i] - x[i - 1];
for (int j = 1;j < K;j++) {
for (int i = 1;i + (1 << j) <= n + 1;i++)
desno[i][j] = min(desno[i][j - 1], desno[i + (1 << (j - 1))][j - 1]);
}
for (int j = 1;j < K;j++) {
for (int i = n;i - (1 << j) >= 0;i--)
levo[i][j] = max(levo[i][j - 1], levo[i - (1 << (j - 1))][j - 1]);
}
auto Close = [&](int s) {
auto u = upper_bound(x + 1, x + n + 1, s) - x;
if (abs(x[u] - s) < abs(x[u - 1] - s))
return u;
return u - 1;
};
cin >> q;
while (q--) {
int s;
cin >> s;
int ans = 0;
int p = Close(s);
ans += abs(x[p] - s);
int l = p, r = p;
int t = p;
while (l != 1 && r != n) {
int np;
if (abs(x[l - 1] - x[t]) <= abs(x[r + 1] - x[t])) {
//idem levo
np = l;
for (int i = K - 1;i >= 0;i--) {
if (levo[np][i] <= x[r + 1]) {
np -= (1 << i);
}
}
l = np;
ans += abs(x[np] - x[t]);
t = np;
}
else {
//idem desno
np = r;
for (int i = K - 1;i >= 0;i--) {
if (desno[np][i] > x[l - 1])
np += (1 << i);
}
r = np;
ans += abs(x[np] - x[t]);
t = np;
}
}
ans += x[n] - x[1];
cout << ans << '\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... |