이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <bits/stdc++.h>
using namespace std;
const int maxn = 200005;
int n, q;
int a[maxn];
int toLeft[maxn];
int toRight[maxn];
int calcLeft(int pos)
{
int l = 1;
int r = pos - 1;
while (l <= r)
{
int mid = (l + r) / 2;
if (a[pos] - a[mid] <= a[pos + 1] - a[pos])
{
r = mid - 1;
}
else
{
l = mid + 1;
}
}
if (l == pos)
{
return -1;
}
else
{
return l;
}
}
int calcRight(int pos)
{
int l = pos + 1;
int r = n;
while (l <= r)
{
int mid = (l + r) / 2;
if (a[mid] - a[pos] < a[pos] - a[pos - 1])
{
l = mid + 1;
}
else
{
r = mid - 1;
}
}
if (r == pos)
{
return -1;
}
else
{
return r;
}
}
long long simulate(int pos)
{
long long ans = 0;
int minPos = pos;
int maxPos = pos;
while (true)
{
if (toLeft[pos] != -1)
{
ans += a[pos] - a[toLeft[pos]];
pos = toLeft[pos];
minPos = min(minPos, pos);
}
else
{
ans += a[toRight[pos]] - a[pos];
pos = toRight[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];
}
for (int i = 1; i <= n; ++i)
{
if (i == 1)
{
toLeft[i] = -1;
toRight[i] = n;
}
else if (i == n)
{
toLeft[i] = 1;
toRight[i] = -1;
}
else
{
toLeft[i] = calcLeft(i);
toRight[i] = calcRight(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);
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... |