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 <bits/stdc++.h>
using namespace std;

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);

    long long n, m, s;
    cin >> n >> m >> s;

    long long p1, p2;
    bool is_p1 = 0, is_p2 = 0;
    vector <pair <long long, long long>> tab(m);
    for(long long i = 0; i < m; i++)
    {
        cin >> tab[i].first >> tab[i].second;
    }
    if(s == 1)
    {
        p2 = 2;
        is_p2 = 1;
    }
    else if(s == n)
    {
        p1 = n - 1;
        is_p1 = 1;
    }
    else
    {
        p1 = s - 1;
        p2 = s + 1;
        is_p1 = 1;
        is_p2 = 1;
    }
    sort(tab.begin(), tab.end(), [s](const pair<long long, long long>& a, const pair<long long, long long>& b) {
        return min(s - a.first, a.second - s) > min(s - b.first, b.second - s);
    });
    for(long long i = 0; i < m; i++)
    {
        if(p1 >= tab[i].first && p1 <= tab[i].second && is_p1)
        {
            p1 = tab[i].first - 1;
        }
        if(p2 >= tab[i].first && p2 <= tab[i].second && is_p2)
        {
            p2 = tab[i].second + 1;
        }
    }
    if(!is_p1) 
    {
        cout << p2 << '\n';
    } 
    else if(!is_p2) 
    {
        cout << p1 << '\n';
    } 
    else 
    {
        if(s - p1 <= p2 - s)
        {
            cout << p1 << '\n';
        }
        else
        {
            cout << p2 << '\n';
        }
    }
}