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
#include <cstdio>
#include <set>
#include <cstdlib>

const long long int INF = 100000000000000;

int main()
{
    int n,m;
    long long int s;
    scanf("%d %d %lld", &n, &m, &s);

    long long int l,r;
    std::set<std::pair<long long int,long long int>> intervals{};
    for(int i=0; i<m; i++)
    {
        scanf("%lld %lld", &l, &r);
        intervals.insert({l,r});
    }

    long long int bestBeforeSchool = INF;
    long long int bestAfterSchool = INF;
    long long int prev_r = 0;
    for(const auto [l,r] : intervals)
    {
        if(l-prev_r > 1L)
        {
            if( l <= s ) bestBeforeSchool = l-1L;
            if( l > s )
            {
                bestAfterSchool = prev_r+1L;
                break;
            }
        }
        prev_r = r;
    }
    if(prev_r<n-1 && bestAfterSchool==INF) bestAfterSchool=prev_r+1L;
    long long int result;
    if(std::abs(s-bestBeforeSchool) <= bestAfterSchool-s) result = bestBeforeSchool;
    else result = bestAfterSchool;

    printf("%lld", result);
    return 0;
}