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

using namespace std;

using ll = long long;

ll dist(ll one, ll other) {
	return max(other - one, one - other);
}

int main() {
	ios_base::sync_with_stdio();
	cin.tie(0);
	ll n, m, s;
	vector<pair<ll, ll>> homes;
	cin >> n >> m >> s;
	ll building = 0;
	ll best = n;
	ll l, r;
	for(int i = 0; i < m; i++) {
		cin >> l >> r;
		homes.push_back({l, r});
	}
	sort(homes.begin(), homes.end());
	auto improve = [&](ll where) {
		ll d = dist(s, where);
		if(d < best) {
			best = d;
			building = where;
		}
	};
	for(int i = 0; i < m; i++) {
		auto [l, r] = homes[i];
		if (l > 1 && (i == 0 || l - 1 > homes[i - 1].second)) {
			improve(l - 1);
		}
		if (r < n && (i == m - 1 || r + 1 < homes[i + 1].first)) {
			improve(r + 1);
		}
	}
	cout << building << "\n";
	return 0;
}