1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <bits/stdc++.h>
using namespace std;
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    int n, m, s;
    cin>>n>>m>>s;

    vector<pair<long long, long long>>tab(m);
    for(int i = 0; i < m; i++){
        cin>>tab[i].first>>tab[i].second;
    }

    sort(tab.begin(), tab.end());
    vector<pair<long long, long long>>spo;
    for(auto &[l,r] : tab){
        if(spo.empty() or spo.back().second < l-1){
            spo.push_back({l, r});
        }
        else{
            spo.back().second = max(spo.back().second, r);
        }
    }
    long long best = -1, dys = n+1;
    for(auto &[l, r] : spo){
        if(s>=l and s<=r){
            if(l>1){
                long long d = s-(l-1);
                if(d < dys or (d == dys and (l-1) < best)){
                    best = l-1;
                    dys = d;
                }
            }
            if(r<n){
                long long d = (r+1)-s;
                if(d < dys or (d == dys and (r+1) < best)){
                    best = r+1;
                    dys = d;
                }
            }
        }
    }
    cout<<best;

}