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
#include <bits/stdc++.h>

using namespace std;
using ll = long long;

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

    ll n, m, s;
    cin >> n >> m >> s;
    vector<pair<ll, ll>> segments(m);
    for (auto &[l, r] : segments) {
        cin >> l >> r;
    }

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

    int idx = 0;
    while (segments[idx].first > s or segments[idx].second < s) {
        ++idx;
    }

    int school_idx = idx;
    while (idx > 0 and segments[idx - 1].second == segments[idx].first - 1) {
        idx--;
    }
    
    ll res = -n;
    if (idx > 0 or segments[idx].first > 1) {
        res = segments[idx].first - 1;
    }

    idx = school_idx;

    while (idx < n - 1 and segments[idx + 1].first == segments[idx].second + 1) {
        idx++;
    }
    if (idx < n - 1 or segments[idx].second < n) {
        if (abs(s - res) > abs(s - segments[idx].second - 1)) {
            res = segments[idx].second + 1;
        }
    }

    cout << res << "\n";
}