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
#include <iostream>
#include <map>

using namespace std;

unsigned long long n, m, s;
unsigned long long a, b;
map <unsigned long long, unsigned long long> toLeft, toRight;
unsigned long long firstToLeft, firstToRight;

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

    cin >> n >> m >> s;

    for (int i = 0; i < m; i++)
    {
        cin >> a >> b;
        if (a <= s && s <= b)
        {
            firstToLeft = a - 1;
            firstToRight = b + 1;
        }
        else
        {
            toLeft[b] = a - 1;
            toRight[a] = b + 1;
        }
    }

    while (toLeft.count(firstToLeft))
    {
        firstToLeft = toLeft[firstToLeft];
    }

    while (toRight.count(firstToRight))
    {
        firstToRight = toRight[firstToRight];
    }

    if (firstToRight > n)
    {
        cout << firstToLeft << '\n';
    }
    else if (firstToLeft < 1)
    {
        cout << firstToRight << '\n';
    }
    else
    {
        if (firstToRight - s < s - firstToLeft)
        {
            cout << firstToRight << '\n';
        }
        else
        {
            cout << firstToLeft << '\n';
        }
    }
    

    return 0;
}