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
#include <bits/stdc++.h>
using namespace std;

#define st first
#define nd second
#define llong long long

llong n, m, s;

vector<pair<llong, llong>> V;

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	
	cin >> n >> m >> s;
	for(int i = 0; i < m; i++) {
		llong l, r;
		cin >> l >> r;
		V.push_back({l, r});
	}
	sort(V.begin(), V.end());
	
	for(int i = m - 1 ; i > 0; i--) {
		if(V[i].st == V[i - 1].nd + 1) 
		{
			V[i - 1].nd = V[i].nd;
			V.erase(V.begin() + i);
		}
	}
	for(auto x : V) {
		if(x.st <= s && s <= x.nd) {
			bool is1valid = x.st - 1 >= 1;
			bool is2valid = x.nd + 1 <= n;
			llong dist = LLONG_MAX;
			llong res;
			if(is1valid) {
				if(s - x.st < dist) {
					dist = s - x.st;
					res = x.st - 1;
				}
			}
			if(is2valid) {
				if(x.nd - s < dist) {
					dist = x.nd - s;
					res = x.nd + 1;
				}
			}
			cout << res << endl;
			return 0;
		}
	}
}