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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <bits/stdc++.h>

#define int long long

using namespace std;

const int mx = 1e12+7;

int n, m, s, budl, budr;

vector<pair<int, int>> v;

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

    cin>>n>>m>>s;

    if (s-1 > 0) {
        budl = s-1;
    }
    else {
        budl = LLONG_MAX;
    }

    if(s+1 < mx) {
        budr = s+1;
    }
    else {
        budr = LLONG_MAX;
    }

    for (int i = 0; i < m; i++) {
        int a, b;
        cin>>a>>b;
        v.push_back({a, b});
    }

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

    for (int i = 0; i < v.size(); i++) {
        int a = v[i].first, b=v[i].second;
        if (budr <= b && budr >= a) {
            budr=b+1;
        }
        if (budl <= b && budl >= a) {
            budl=a-1;
        }
    }

    if (budr > n) {
        budr=LLONG_MAX;
    }

    sort(v.begin(), v.end(), greater());

    for (int i = 0; i < v.size(); i++) {
        int a = v[i].first, b=v[i].second;
        if (budr <= b && budr >= a) {
            budr=b+1;
        }
        if (budl <= b && budl >= a) {
            budl=a-1;
        }
    }

    if (budl < 1) {
        budl=LLONG_MAX;
    }

    if (abs(s-budl) == abs(s-budr)) {
        cout<<budl;
    }
    else if (abs(s-budl) < abs(s-budr)) {
        cout<<budl;
    }
    else {
        cout<<budr;
    }

}