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
46
47
#include <bits/stdc++.h>
using namespace std;

#define int long long

#define st first
#define nd second

main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int n,m,s;
    cin>>n>>m>>s;
    vector<pair<int,int>> comps;
    for(int i=0; i<m; i++) {
        int a,b;
        cin>>a>>b;
        comps.push_back({a,b});
    }
    sort(comps.begin(),comps.end());
    int ind=0;
    for(; ind<comps.size(); ind++) {
        if(comps[ind].st<=s && comps[ind].nd>=s) break;
    }
    int r = -1;
    for(int i=ind+1; i<comps.size()-1; i++) {
        if(comps[i-1].nd+1<comps[i].st) {
            r=comps[i-1].nd+1;
            break;
        }
    }
    if(r==-1 && comps.back().nd != n) r=comps.back().nd+1;

    int l = -1;
    for(int i=ind-1; i>=0; i--) {
        if(comps[i].nd+1<comps[i+1].st) {
            l=comps[i+1].st-1;
            break;
        }
    }
    if(l==-1 && comps.front().st != 1) l=comps.front().st-1;
    int res = l;
    if(res == -1 || (r!= -1 && (r-s)<(s-l))) res = r;
    cout<<res;

}