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
83
84
85
86
87
88
89
90
91
#ifdef _WIN32
#include <io.h>
#include <fcntl.h>
#endif

#include <assert.h>
#include <iostream>
#include <stdint.h>

typedef int64_t i64;

const i64 MaxN = 1000000000000;
const int MaxM = 1000;

i64 N;
int M;
i64 S;
i64 L[MaxM] = { 0 };
i64 R[MaxM] = { 0 };

int znajdz_przedzial(i64 Dom)
{
    for (int i = 0; i < M; i++) {
        if (L[i] <= Dom && Dom <= R[i]) {
            return i;
        }
    }
    return -1;    
}

i64 szukaj_lewo()
{
    i64 Lewy = S - 1;
    while (Lewy > 0) {
        int Przedzial = znajdz_przedzial(Lewy);
        if (Przedzial < 0) {
            break;
        }
        Lewy = L[Przedzial] - 1;
    }
    return Lewy;
}

i64 szukaj_prawo()
{
    i64 Prawy = S + 1;
    while (Prawy <= N) {
        int Przedzial = znajdz_przedzial(Prawy);
        if (Przedzial < 0) {
            break;
        }
        Prawy = R[Przedzial] + 1;
    }
    return Prawy;
}

int main()
{
    std::ios_base::sync_with_stdio(false);
    std::cin.tie(NULL);

#ifdef _WIN32
    _setmode( _fileno( stdout ),  _O_BINARY );
#endif

    std::cin >> N >> M >> S;
    for (int i = 0; i < M; i++) {
        std::cin >> L[i] >> R[i];
    }

    i64 Lewy = szukaj_lewo();
    i64 Prawy = szukaj_prawo();

    i64 Wynik = 0;
    if (Lewy > 0 && Prawy <= N) {
        if (S - Lewy <= Prawy - S) {
            Wynik = Lewy;
        } else {
            Wynik = Prawy;
        }
    } else if (Lewy > 0) {
        Wynik = Lewy;
    } else if (Prawy <= N) {
        Wynik = Prawy;
    }

    std::cout << Wynik << '\n';
    std::cout.flush();

    return 0;
}