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

const ll inf  = 1e18 + 13; 
ll n, m, s;
vector<pair<ll, ll>> v, v1, v2; 
bool comp2(pair<ll, ll> a, pair<ll, ll>b)
{
    return a.first < b.first || (a.first == b.first && a.second < b.second); 
}
bool comp1(pair<ll, ll> a, pair<ll, ll>b)
{
    return a.second > b.second || (a.second == b.second && a.first > b.first); 
}
void rozdziel()
{
    for(int i = 0; i < v.size(); i++)
    {
        pair<ll, ll> a1 = {min(v[i].first, s), min(v[i].second, s)};
        pair<ll, ll> a2 = {max(v[i].first, s), max(v[i].second, s)};
        if(a1 != make_pair(s, s))
            v1.push_back(a1);
        if(a2 != make_pair(s, s))
            v2.push_back(a2);
    }
}
int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);

    cin >> n >> m >> s;
    for(int i = 0; i < m; i++)
    {
        ll a, b;
        cin >> a >> b;
        v.push_back({a, b}); 
    }
    rozdziel();

    ll mx = s + 1;
    sort(v2.begin(), v2.end(), comp2);
    for(int i = 0; i < v2.size(); i++)
        if(v2[i].first <= mx)
            mx = max(mx, v2[i].second + 1);
        else
            break;
    
    ll mn = s - 1;
    sort(v1.begin(), v1.end(), comp1);
    for(int i = 0; i < v1.size(); i++)
        if(v1[i].second >= mn)
            mn = min(mn, v1[i].first - 1);
        else
            break;
    if(mn <= 0)
        mn = -inf;
    if(mx > n)
        mx = inf;
    if(s - mn <= mx - s)
        cout << mn;
    else
        cout << mx;
    cout << '\n';
}