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
#include <algorithm>
#include <cstdio>
#include <limits>
#include <vector>

using numer = long long;

struct Przedzial
{
    numer l, r;
    bool operator<(const Przedzial& p) const {
	return l < p.l;
    }
};

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

    std::vector<Przedzial> zajete;
    zajete.resize(m+2);
    for (int i=0; i<m; ++i) {
	scanf("%lld%lld", &zajete[i].l, &zajete[i].r);
    }
    zajete[m] = { 0, 0 };
    zajete[m+1] = { n+1, n+1 };
    std::sort(zajete.begin(), zajete.end());

    numer best_numer = 0;
    numer best_distance = std::numeric_limits<numer>::max();
    for (int i=0; i<=m; ++i) {
	numer wolne_l = zajete[i].r + 1;
	numer wolne_r = zajete[i+1].l - 1;
	if (wolne_l <= wolne_r) {
	    numer kandydat = (wolne_r < s) ? wolne_r : wolne_l;
	    numer distance = std::abs(kandydat - s);

	    if (distance < best_distance) {
		best_numer = kandydat;
		best_distance = distance;
	    }
	}
    }
    printf("%lld\n", best_numer);
}