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
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define UwU cin.tie(0); cout.tie(0); ios::sync_with_stdio(0);


ll closestPoint(ll x, pair<ll, ll> rng) {
    if (x >= rng.first && x <= rng.second) return x; 
    
    if(x <= rng.first) return rng.first;
    return rng.second;
}

ll updateBest(ll best, ll candidate, ll s) {
    if (best < 0) return candidate;
    ll distBest = llabs(s - best);
    ll distCand = llabs(s - candidate);
   
    if (distCand < distBest || (distCand == distBest && candidate < best)) {
        return candidate;
    }
    return best;
}

int main() {
    UwU;
    ll n, m, s;
    cin >> n >> m >> s;

    vector<pair<ll, ll>> zaj(m);
    for (int i = 0; i < m; i++) {
        cin >> zaj[i].first >> zaj[i].second;
    }
    sort(zaj.begin(), zaj.end());
   
    vector<pair<ll, ll>> wolne;
    if (zaj[0].first > 1) 
        wolne.push_back({1, zaj[0].first - 1});

    for (int i = 0; i < m - 1; i++) {
        ll leftGap = zaj[i].second + 1;
        ll rightGap = zaj[i+1].first - 1;
        if (leftGap <= rightGap) 
            wolne.push_back({leftGap, rightGap});
    }
   
    if (zaj[m - 1].second < n) 
        wolne.push_back({zaj[m - 1].second + 1, n});
    
    sort(wolne.begin(), wolne.end());

    vector<ll> wolne2;
    for(auto i: wolne) wolne2.push_back(i.second);

    int pos = int(lower_bound(wolne2.begin(), wolne2.end(), s) - wolne2.begin());
    ll best = -1;

    if (pos < wolne.size()) 
        best = updateBest(best, closestPoint(s, wolne[pos]), s);
    if (pos > 0) 
        best = updateBest(best, closestPoint(s, wolne[pos - 1]), s);
    cout << best << "\n";
    return 0;
}