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
 
 
 signed main(){
    int n, m, q; cin >> n >> m >> q;
    set<int> val;
    for (int i = 0; i < m; i++){
        int x; cin >> x;
        val.insert(x);
        if (x <= n - 1) val.insert(x + n);
        else val.insert(x - n);
    }
    while(q--){
        int x, y; cin >> x >> y;
        if (x > y) swap(x, y);
        int ans = min(y- x, 2 * n - y + x);
        auto it = val.upper_bound(x);
        if (it != val.end()){
            int new_x = *it;
            int extra = abs(new_x - x);
            
            if (*it >= n) new_x -= n;
            else new_x += n;
            
            int new_y = y;
            if (new_x > new_y) swap(new_x, new_y);
            ans = min(ans, new_y - new_x + 1 + extra);
            ans = min(ans, 2 * n - new_y + new_x + 1 + extra);
        }
        if (it != val.begin()){
            it--;
            int new_x = *it;
            int extra = abs(new_x - x);
            
            if (*it >= n) new_x -= n;
            else new_x += n;
            
            int new_y = y;
            if (new_x > new_y) swap(new_x, new_y);
            ans = min(ans, new_y - new_x + 1 + extra);
            ans = min(ans, 2 * n - new_y + new_x + 1 + extra);
        }
        
        if (!val.empty()){
            auto it = val.begin();
            int new_x = *it;
            int extra = min(2 * n - abs(new_x - x),abs(new_x - x));
            
            if (*it >= n) new_x -= n;
            else new_x += n;
            
            int new_y = y;
            if (new_x > new_y) swap(new_x, new_y);
            ans = min(ans, new_y - new_x + 1 + extra);
            ans = min(ans, 2 * n - new_y + new_x + 1 + extra);
        }
        
        if (!val.empty()){
            auto it = val.end();
            it--;
            int new_x = *it;
            int extra = min(2 * n - abs(new_x - x),abs(new_x - x));
            
            if (*it >= n) new_x -= n;
            else new_x += n;
            
            int new_y = y;
            if (new_x > new_y) swap(new_x, new_y);
            ans = min(ans, new_y - new_x + 1 + extra);
            ans = min(ans, 2 * n - new_y + new_x + 1 + extra);
        }
        
        cout << ans << 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... |