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

int main(){
	ios_base::sync_with_stdio(0);
	cout.tie(0); cin.tie(0);
	
	ll n, m, s; cin>>n>>m>>s;
	set<vector<ll>> datei;

	vector<pair<ll, ll>> inp(m);
	for(ll i=0; i<m; i++){
		cin>>inp[i].first>>inp[i].second;
	}

	sort(inp.begin(), inp.end());

	ll lastleft = inp[0].first, lastright = inp[0].second;
	for(ll i=1; i<m; i++){
		if(inp[i].first != lastright+1){
			datei.insert({lastright, 1, lastleft});
			lastleft = inp[i].first;
		}

		lastright = inp[i].second;
	}

	datei.insert({lastright, 1, lastleft});

	if(datei.lower_bound({s, 0, 0}) == datei.end()){
		cout<<s;
		return 0;
	}

	vector<ll> it = *datei.lower_bound({s, 0, 0});

	ll rightcand = (it[0]) + 1;	
	ll leftcand = (it[2]) - 1;

	ll dstone = rightcand - s;
	ll dsttwo = s - leftcand;	

	if(rightcand == n+1) dstone = LONG_LONG_MAX;
	if(leftcand == 0) dsttwo = LONG_LONG_MAX;


	if(s <= leftcand) cout<<s;
	else if(dstone < dsttwo) cout<<rightcand;
	else cout<<leftcand;
	

	return 0;
}