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
#include <bits/stdc++.h>
using namespace std;
int main()
{
	ios_base::sync_with_stdio(NULL);
	cin.tie(NULL);
	cout.tie(NULL);
	long long int n,m,s;
	cin>>n>>m>>s;
	vector<pair<long long int,long long int>>v1,v2;
	for(int i=0; i<m; i++)
	{
		long long int l,r;
		cin>>l>>r;
		if(l<=s&&s<=r)
		{//cout<<l<<" "<<r<<"hh\n";
			v1.push_back({0-r,0-l});
			v2.push_back({l,r});
		}
		if(s<l)
			v2.push_back({l,r});
		if(r<s)
			v1.push_back({0-r,0-l});
	}
	long long int wyn=-1;
	long long int odl=n+1;
	sort(v1.begin(),v1.end());
	sort(v2.begin(),v2.end());
	long long int ost=s;
	for(int i=0; i<v1.size(); i++)
	{
		if(ost-1>0-v1[i].first&&ost-1>0)
		{
			wyn=ost-1;//cout<<wyn<<"q\n";
			odl=s-wyn;
			break;
		}
		ost=min(ost,0-v1[i].second);
	}
	if(ost-1>0)
	{
		wyn=ost-1;//cout<<wyn<<"q\n";
		odl=s-wyn;
	}
	ost=s;
	for(int i=0; i<v2.size(); i++){
		if(ost+1<v2[i].first&&ost+1<=n)
		{
			if(ost+1-s<odl)
			{
				wyn=ost+1;
				odl=wyn-s;
				break;
			}
		}
		ost=max(ost,v2[i].second);
	}
	if(ost+1<=n)
		if(ost+1-s<odl)
		{
			wyn=ost+1;
			odl=wyn-s;
		}
	cout<<wyn<<"\n";
}