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

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    long long n, s;
    int d;
    cin >> n >> d >> s;

    vector<pair<long long, long long>> occupancies(d);

    while (d--)
        cin >> occupancies[d].first >> occupancies[d].second;
    occupancies.emplace_back(0, 0);
    occupancies.emplace_back(n+1, n+1);

    sort(occupancies.begin(), occupancies.end());

    long long best = -1000000000000000L;

    auto update_best = [&best, s](long long c) {
        if (abs(s - best) > abs(s - c))
            best = c;
        if (abs(s - best) == abs(s - c) && c < best)
            best = c;
    };

    for (int i = 1; i < occupancies.size() - 1; ++i) {
        if (occupancies[i - 1].second != occupancies[i].first - 1)
            update_best(occupancies[i].first - 1);
        if (occupancies[i + 1].first != occupancies[i].second + 1)
            update_best(occupancies[i].second + 1);
    }

    cout << best << endl;
}