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

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    long long n, m, s; cin >> n >> m >> s;
    vector<pair<long long, long long>> segm(m);
    for (auto &x : segm) {
        cin >> x.first >> x.second;
    }
    sort(segm.begin(), segm.end());
    long long mx = n + 1, x = -1;
    auto upd = [&](long long l, long long r) {
        if (abs(s - l) < mx) {
            mx = abs(s - l);
            x = l;
        }
        if (l <= s && r >= s) {
            mx = 0;
            x = s;
        }
        if (abs(s - r) < mx) {
            mx = abs(s - r);
            x = r;
        }
    };
    if (segm[0].first != 1) {
        upd(1, segm[0].first - 1);  
    }
    for (int i = 1; i < m; i++) {
        if (segm[i].first - 1 != segm[i - 1].second) {
            upd(segm[i - 1].second + 1, segm[i].first - 1);
        }
    }
    if (segm[m - 1].second != n) {
        upd(segm[m - 1].second + 1, n);
    }
    cout << x << "\n";
}