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
54
55
56
57
#include <bits/stdc++.h>
using namespace std;

vector<pair<long long, long long>> cand;
vector<long long> c;
long long dist = LLONG_MAX;
long long best;
long long n, m, s;

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);

    cin >> n >> m >> s;

    for(int i = 0; i < m; i++) {
        long long l, r;
        cin >> l >> r;
        cand.push_back({l, r});
    }

    sort(cand.begin(), cand.end());

    for(int i = 0; i < m; i++) {

        if(i == 0 && cand[i].first - 1 > 1) {
            c.push_back(cand[i].first - 1);
            continue;
        }

        if(i == m - 1 && cand[i].second + 1 < n) {
            c.push_back(cand[i].second + 1);
            continue;
        }

        if(cand[i].first - 1 > 0 && cand[i - 1].second != cand[i].first - 1) {
            c.push_back(cand[i].first - 1);
        }

        if(cand[i].second + 1 <= n && cand[i + 1].first != cand[i].second + 1) {
            c.push_back(cand[i].second + 1);
        }
    }

    for(long long x : c) {
        long long d = abs(s - x);

        if(d == dist) {
            best = min(best, x);
        } else if(d < dist) {
            dist = d;
            best = x;
        }
    }

    cout << best << '\n';
}