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;
const int maxn = 200005;
int n, q;
int a[maxn];
long long simulate(int pos)
{
long long ans = 0;
int minPos = pos;
int maxPos = pos;
while (true)
{
//cout << "now " << pos << endl;
//for (int i = 0; i < 1e9; ++i);
if (pos == 1)
{
ans += (a[n] - a[1]);
maxPos = n;
}
else if (pos == n)
{
ans += (a[n] - a[1]);
minPos = 1;
}
else
{
//cout << "decide " << pos << " " << minPos << " " << maxPos << endl;
if (a[pos] - a[minPos - 1] <= a[maxPos + 1] - a[pos]) // go left
{
//cout << "LEFT" << endl;
int l = 1;
int r = pos - 1;
while (l <= r)
{
int mid = (l + r) / 2;
if (a[pos] - a[mid] <= a[maxPos + 1] - a[pos])
{
r = mid - 1;
}
else
{
l = mid + 1;
}
}
ans += (a[pos] - a[l]);
pos = l;
}
else // go right
{
//cout << "RIGHT" << endl;
int l = pos + 1;
int r = n;
while (l <= r)
{
int mid = (l + r) / 2;
if (a[mid] - a[pos] < a[pos] - a[minPos - 1])
{
l = mid + 1;
}
else
{
r = mid - 1;
}
}
ans += (a[r] - a[pos]);
pos = r;
}
minPos = min(minPos, pos);
maxPos = max(maxPos, pos);
}
if (minPos == 1 && maxPos == n)
{
break;
}
}
return ans;
}
void fastIO()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
}
int main()
{
fastIO();
cin >> n;
for (int i = 1; i <= n; ++i)
{
cin >> a[i];
}
cin >> q;
for (int i = 1; i <= q; ++i)
{
int x;
cin >> x;
int nxt = lower_bound(a + 1, a + n + 1, x) - a;
int prv = nxt - 1;
int where = -1;
if (prv <= 0)
{
where = nxt;
}
else if (nxt > n)
{
where = prv;
}
else
{
if (x - a[prv] <= a[nxt] - x)
{
where = prv;
}
else
{
where = nxt;
}
}
int dist1 = abs(a[where] - x);
if (n == 1)
{
cout << dist1 << "\n";
continue;
}
long long ans = dist1 + simulate(where);
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... |