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

using namespace std;

int main() {
    int numHouses, numIntervals, school, leftmost, rightmost;
    const int inf {0xFFFFFFF};

    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    cin >> numHouses >> numIntervals >> school;
    vector<int> left(numIntervals + 2, 0), right(numIntervals + 2, 0);

    for (int i=1; i<=numIntervals; ++i) {
        cin >> left[i] >> right[i];
    }
    left[numIntervals + 1] = right[numIntervals + 1] = inf;

    sort(left.begin(), left.end());
    sort(right.begin(), right.end());
 
    leftmost = rightmost = lower_bound(right.begin(), right.end(), school) - right.begin();

    while (left[leftmost] && right[leftmost - 1] == left[leftmost] - 1) {
        --leftmost;
    }

    while (right[rightmost] && left[rightmost + 1] == right[rightmost] + 1) {
        ++rightmost;
    }

    if (right[rightmost] == numHouses) {
        cout << left[leftmost] - 1;
    }
    else if (left[leftmost] == 0) {
        cout << right[rightmost] + 1;
    }
    else if (school - left[leftmost] <= right[rightmost] - school) {
        cout << left[leftmost] - 1;
    }
    else {
        cout << right[rightmost] + 1;
    }

    return 0;
}