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
48
49
50
51
52
53
#include <bits/stdc++.h>

using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    long long n, m, s;
    cin>>n>>m>>s;

    vector<pair<long long, long long>> ranges;

    for(int i=0;i<m;i++) {
        long long l, r;
        cin>>l>>r;
        ranges.push_back(make_pair(l, r));
    }
    sort(ranges.begin(), ranges.end());
    long long pos = -n-1;
    if(ranges[0].first > 1) {
        pos = ranges[0].first-1;
        // cout << "zmiana0 " << pos << endl;
    }
    for(int i=0;i<ranges.size()-1;i++) {
        if(pos > 0) {
            if (ranges[i].second + 1 != ranges[i+1].first) {
                long long better = abs(s - (ranges[i].second + 1)) < abs(s - (ranges[i+1].first - 1))?ranges[i].second+1:ranges[i+1].first - 1;
                pos = abs(s - better) < abs(s - pos)?better:pos;
                // cout << "zmiana1 " << pos << endl;
            }
        }else {
            if (ranges[i].second + 1 != ranges[i+1].first) {
                pos = abs(s - (ranges[i].second + 1)) < abs(s - (ranges[i+1].first - 1))?ranges[i].second+1:ranges[i+1].first - 1;
                // cout << "zmiana2 " << pos << endl;
            }
        }
    }
    if(ranges[ranges.size() - 1].second < n) {
        // cout << s << endl;
        // cout << ranges[ranges.size() - 1].second+1 << endl;
        // cout << s - (ranges[ranges.size() - 1].second+1) << endl;
        // cout << pos << endl;
        // cout << s - pos << endl;
        if(pos > 0) {
            pos = abs(s - (ranges[ranges.size() - 1].second+1))<abs(s-pos)?ranges[ranges.size() - 1].second+1:pos;
        }else {
            pos = ranges[ranges.size() - 1].second+1;
        }
        // cout << "zmiana3 " << pos << endl;
    }
    cout<<pos<<endl;
    return 0;
}