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 ll long long
#define all(x) x.begin(),x.end()
#define sor(x) sort(all(x))
#define pi pair<int,int>
#define vi vector<int>
#define pb push_back
#define int ll
int N,M,Q;
void solve() {
    cin >> N >> M >> Q;
    vi bestfriend{0};
    for (int i = 0; i < M;++i) {
        int b = 0;
        cin >> b;
        bestfriend.pb(b + 1);
        bestfriend.pb(b + N + 1);
        }
    auto Do = [&] (int a,int b) {
        if (a > 2 * N)
            a -= 2 * N;
        if (a > b)
            swap(a,b);
        int ans = (int)1e12;
        ans = b - a;
        ans = min(ans,a + 2 * N - b);
        return ans;
    };
    sor(bestfriend);
    while(Q--) {
        int a,b; cin >> a >> b;
        ++a,++b;
        int ans = Do(a,b);
        if(bestfriend.size() == 1) {
            cout << ans << '\n';
            continue;
        }
        int l = 1,r = bestfriend.size() - 1;
        int p = -1;
        while (l <= r) {
            int mid = (l + r) / 2;
            //cout << mid << ' ' << bestfriend[mid] << '\n';
            if (bestfriend[mid] <= a) {
                p = mid;
                l = mid + 1;
            } else {
                r = mid - 1;
            }
        }
        if(p == -1) {
            ans = min(ans,Do(bestfriend.back() - N,b) + a + 1 + 2 * N - bestfriend.back());
            ans = min(ans,Do(bestfriend[1] + N,b) + bestfriend[1] - a + 1);
        }
        if(p != -1){
            ans = min(ans,Do(N + bestfriend[p],b) + a - bestfriend[p] + 1);
            if (p + 1 == bestfriend.size())  {
                ans = min(ans,Do(N + bestfriend[1],b) + 2 * N - a + bestfriend[1] + 1);
            }
            else ans = min(ans,Do(N + bestfriend[p + 1],b) + bestfriend[p + 1] - a + 1);
        }
        cout << ans << "\n";
    }
}
main(){
    solve();
}
Compilation message (stderr)
Main.cpp: In function 'void solve()':
Main.cpp:58:23: warning: comparison of integer expressions of different signedness: 'long long int' and 'std::vector<long long int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
   58 |             if (p + 1 == bestfriend.size())  {
      |                 ~~~~~~^~~~~~~~~~~~~~~~~~~~
Main.cpp: At global scope:
Main.cpp:67:1: warning: ISO C++ forbids declaration of 'main' with no type [-Wreturn-type]
   67 | main(){
      | ^~~~| # | 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... |