#include <cstdio>
#include <cstdint>
#include <vector>
#include <bitset>
#include <tuple>
#include <algorithm>
#include <climits>
using namespace std;
long long n,m,s;
vector<pair<long long, long long>> vec;
int main ()
{
scanf("%lld %lld %lld", &n, &m, &s);
vec.push_back(make_pair(-1, 0));
for(int i = 0; i < m; ++i)
{
long long a,b;
scanf("%lld %lld",&a,&b);
vec.push_back(make_pair(a,b));
}
vec.push_back(make_pair(n+1, n+2));
sort(vec.begin(), vec.end());
long long bestDistance = LLONG_MAX;
long long bestP = -2;
for (int i = 1; i<=m; ++i)
{
if (vec[i-1].second < vec[i].first - 1)
{
long long lastFree = vec[i].first - 1;
//there is a gap before
long long currentDistance = abs(s - lastFree);
if(currentDistance < bestDistance)
{
bestP = lastFree;
bestDistance = currentDistance;
}
}
if (vec[i].second < vec[i+1].first - 1)
{
long long lastFree = vec[i].second + 1;
//there is a gap after
long long currentDistance = abs(s - lastFree);
if(currentDistance < bestDistance)
{
bestP = lastFree;
bestDistance = currentDistance;
}
}
}
printf("%lld\n", bestP);
}
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 | #include <cstdio> #include <cstdint> #include <vector> #include <bitset> #include <tuple> #include <algorithm> #include <climits> using namespace std; long long n,m,s; vector<pair<long long, long long>> vec; int main () { scanf("%lld %lld %lld", &n, &m, &s); vec.push_back(make_pair(-1, 0)); for(int i = 0; i < m; ++i) { long long a,b; scanf("%lld %lld",&a,&b); vec.push_back(make_pair(a,b)); } vec.push_back(make_pair(n+1, n+2)); sort(vec.begin(), vec.end()); long long bestDistance = LLONG_MAX; long long bestP = -2; for (int i = 1; i<=m; ++i) { if (vec[i-1].second < vec[i].first - 1) { long long lastFree = vec[i].first - 1; //there is a gap before long long currentDistance = abs(s - lastFree); if(currentDistance < bestDistance) { bestP = lastFree; bestDistance = currentDistance; } } if (vec[i].second < vec[i+1].first - 1) { long long lastFree = vec[i].second + 1; //there is a gap after long long currentDistance = abs(s - lastFree); if(currentDistance < bestDistance) { bestP = lastFree; bestDistance = currentDistance; } } } printf("%lld\n", bestP); } |
English