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
#include <algorithm>
#include <cstdio>
#include <ios>
#include <vector>
using namespace std;

struct budyneczki {
    long long start;
    long long end;

    bool operator<(const budyneczki &other) const {
        return start < other.start;
    }
};

vector<budyneczki> miasto;

int main() {
    long long n, m, s;
    scanf("%lld %lld %lld", &n, &m, &s);
    for (int i = 0; i < m; ++i) {
        long long x, y;
        scanf("%lld %lld", &x, &y);
        miasto.push_back(budyneczki{x, y});
    }
    sort(miasto.begin(), miasto.end());
    int szkolasegment = -1;
    for (int i = 0; i < m; ++i) {
        if (s <= miasto[i].end && s >= miasto[i].start) {
            szkolasegment = i;
            break;
        }
    }
    long long left_dist = n + 1;
    long long right_dist = n + 1;

    long long left_id = -1;
    long long right_id = -1;
    for (int i = szkolasegment; i >= 1; --i) {
        if (miasto[i-1].end < miasto[i].start - 1) {
            left_dist = s - miasto[i].start + 1;
            left_id = miasto[i].start - 1;
            // printf("%lld is the best left-house\n", miasto[i].start - 1);
            break;
        }
    }
    if (left_dist == n+1) {
        if (miasto[0].start != 1) {
            left_dist = s - miasto[0].start + 1;
            left_id = miasto[0].start - 1;
            // printf("%lld is the best left-house\n", miasto[0].start - 1);
        } else {
            // printf("No free left-house!\n");
        }
    }

    for (int i = szkolasegment; i < m - 1; ++i) {
        if (miasto[i+1].start > miasto[i].end + 1) {
            right_dist = miasto[i].end - s + 1;
            right_id = miasto[i].end + 1;
            // printf("%lld is the best right-house\n", miasto[i].end + 1);
            break;
        }
    }
    if (right_dist == n+1) {
        if (miasto[m-1].end != n) {
            right_dist = miasto[m-1].end - s + 1;
            right_id = miasto[m-1].end + 1;
            // printf("%lld is the best right-house\n", miasto[m-1].end + 1);
        } else {
            // printf("No free right-house!\n");
        }
    }

    long long best_id = left_id;
    if (right_dist < left_dist) best_id = right_id;

    printf("%lld\n", best_id);

    return 0;
}