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
#include <iostream>
#include <cstdint>
#include <map>

namespace {
    using int_t = int64_t;
    using przedzialy_t = std::map<int_t, int_t>;

    using std::cout, std::cin;
}

int main() {
    int_t n, m, s;
    int_t li, ri;
    int_t max_l = 0, min_p = 0;
    przedzialy_t lewe, prawe;

    cin >> n >> m >> s;
    if (s > 1) max_l = s - 1;
    if (s < n) min_p = s + 1;;
    for (int_t i = 1; i <= m; ++i) {
        cin >> li >> ri;

        if (li <= max_l && max_l <= ri)
            max_l = li - 1;
        else if (li < max_l)
            lewe.insert({li, ri});

        if (li <= min_p && min_p <= ri) {
            if (ri < n) min_p = ri + 1;
            else min_p = 0;
        } else if (min_p < li) {
            prawe.insert({li, ri});
        }
    }

    if (!lewe.empty()) {
        auto it = lewe.rbegin();
        bool koniec = false;
        while (!koniec && it != lewe.rend()) {
            if (it->first <= max_l && max_l <= it->second) {
                max_l = it->first - 1;
                ++it;
            } else {
                koniec = true;
            }
        }
    }

    if (!prawe.empty()) {
        auto it = prawe.begin();
        bool koniec = false;
        while (!koniec && it != prawe.end()) {
            if (it->first <= min_p && min_p <= it->second) {
                if (it->second < n) min_p = it->second + 1;
                else min_p = 0;
                ++it;
            } else {
                koniec = true;
            }
        }
    }

    if (!min_p)
        cout << max_l << '\n';
    else if (!max_l)
        cout << min_p << '\n';
    else
        cout << (s - max_l <= min_p - s ? max_l : min_p) << '\n';
}