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
#include <algorithm>
#include <iostream>
#include <tuple>
#include <utility>
#include <vector>
using ll = long long;

int main() {
	std::ios_base::sync_with_stdio(0); std::cin.tie(0);
	
	ll n;
	int m;
	ll s;
	std::cin >> n >> m >> s;
	
	ll INFTY = 10 * n; // 2*n is enough i think but who cares
	
	std::vector<std::pair<ll, ll>> segs(m);
	
	for (int i = 0; i < m; ++i) {
		ll l, r;
		std::cin >> l >> r;
		segs[i] = {l, r};
	}
	
	std::sort(segs.begin(), segs.end());
	
	for (int i = 0; i < m; ++i) {
		auto [l, r] = segs[i];
		if (s < l || r < s) continue;
		
		int j = i;
		while (j > 0 && segs[j-1].second == segs[j].first - 1) {
			--j;
		}
		
		ll candidate_left = -INFTY;
		
		if (segs[j].first > 1) {
			candidate_left = segs[j].first - 1;
		}
		
		j = i;
		while (j < m-1 && segs[j+1].first == segs[j].second + 1) {
			++j;
		}
		
		ll candidate_rite = +INFTY;
		
		if (segs[j].second < n) {
			candidate_rite = segs[j].second + 1;
		}
		
//		std::cout << "candidate_left="<<candidate_left<<", candidate_rite="<<candidate_rite<<'\n';
		
		if (s - candidate_left <= candidate_rite - s) {
			std::cout << candidate_left << '\n';
		} else {
			std::cout << candidate_rite << '\n';
		}
		
		return 0;
	}
	
	// the statement says the school always lies in a segment.
	__builtin_unreachable();
}