#include <bits/stdc++.h>
using namespace std;
#define int long long
const int MAX = 500007;
const int INF = LLONG_MAX;
int N;
int distance(int x, int y) {
int dist = abs(x-y);
dist = min(dist, 2*N-dist);
return dist;
}
int get_opposite(int x) {
if (x%N == x) return x + N;
else return x % N;
}
int32_t main() {
ios::sync_with_stdio(0);
cin.tie(0);
int M,Q;
cin >> N >> M >> Q;
int best_friend[M]; //other best_friend is +N
int best_friend_bsta[M*2+3];
for (int i=0;i<M;i++) {
cin >> best_friend[i];
best_friend_bsta[i+1] = best_friend[i];
best_friend_bsta[i+M+1] = best_friend[i]+N;
}
best_friend_bsta[0] = -1;
best_friend_bsta[2*M+1] = INF;
int bridge_is_totally_useless_radius = (N+1)/2;
int bridge_is_useless_radius = N/2-1;
int x, y;
for (int i=0;i<Q;i++) {
cin >> x >> y;
if (distance(x,y)<=bridge_is_totally_useless_radius) {
cout << distance(x,y) << endl;
} else {
int shortest_path = distance(x,y);
// binary search for closest neighbours
int lo = 0; int hi = 2*M+1; int mid;
int left;
while (lo <= hi) {
mid = lo + (hi-lo) /2;
if (best_friend_bsta[mid] > x)
{hi = mid-1; left = hi;}
else {
lo = mid+1;
left = mid;
}
}
lo = 0; hi = 2*M+1;
int right;
while (lo <= hi) {
mid = lo + (hi-lo) /2;
if (best_friend_bsta[mid] < x)
{lo = mid+1;
right = lo;
}
else {
hi = mid-1;
right = mid;
}
}
int left_bestie, right_bestie;
left_bestie = best_friend_bsta[left];
right_bestie = best_friend_bsta[right];
if (left == 0) left_bestie = best_friend_bsta[2*M];
if (right == 2*M+1) right_bestie = best_friend_bsta[1];
shortest_path = min(shortest_path,distance(left_bestie,x) + distance(get_opposite(left_bestie),y) + 1);
shortest_path = min(shortest_path,distance(right_bestie,x) + distance(get_opposite(right_bestie),y) + 1);
cout << shortest_path << endl;
}
}
}
# | 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... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |