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
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

#define LL long long
#define REP(i,n)  for (int i = 0; i < n; i++)

struct Interval {
    LL l, r;
};

class EmptyHouseFinder {
    LL n{}, m{}, s{};
    vector<Interval> intervals;

public:
    void solve() {
        cin >> n >> m >> s;
        intervals.resize(m);

        REP(i, m) {
            cin >> intervals[i].l >> intervals[i].r;
        }

        sort(intervals.begin(), intervals.end(), [](const Interval &a, const Interval &b) {
            return a.l < b.l;
        });

        vector<Interval> merged;
        REP(i, m) {
            if (merged.empty() || intervals[i].l > merged.back().r + 1) {
                merged.push_back(intervals[i]);
            } else {
                merged.back().r = max(merged.back().r, intervals[i].r);
            }
        }

        Interval target;
        for (const auto &intv: merged) {
            if (intv.l <= s && s <= intv.r) {
                target = intv;
                break;
            }
        }

        LL candidateLeft = (target.l > 1) ? target.l - 1 : -1;
        LL candidateRight = (target.r < n) ? target.r + 1 : -1;
        LL ans;

        if (candidateLeft == -1) {
            ans = candidateRight;
        } else if (candidateRight == -1) {
            ans = candidateLeft;
        } else {
            LL distLeft = s - candidateLeft;
            LL distRight = candidateRight - s;
            ans = (distLeft <= distRight) ? candidateLeft : candidateRight;
        }

        cout << ans << endl;
    }
};

int main() {
    EmptyHouseFinder house_finder;
    house_finder.solve();

    return 0;
}