#include <iostream>
#include <algorithm>
#include <vector>
#include <climits>
using namespace std;
bool pairComp(const pair<int, int>& a, const pair<int, int>& b) {
return a.first < b.first;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
int m;
int s;
cin >> n >> m >> s;
vector<pair<int, int>> occupied;
int a, b;
for (int i = 0; i < m; i++) {
cin >> a >> b;
occupied.push_back({ a, b });
}
sort(occupied.begin(), occupied.end(), pairComp);
occupied.insert(occupied.begin(), { -1, 0 });
occupied.push_back({ n + 1, n + 2 });
int nearest = -1;
int val = INT_MAX;
for (int i = 1; i < m + 1; i++) {
if (occupied[i-1].second != occupied[i].first - 1) {
int dist = abs(occupied[i].first - 1 - s);
if (dist < val) {
nearest = occupied[i].first - 1;
val = dist;
}
}
if (occupied[i].second + 1 != occupied[i + 1].first) {
int dist = abs(occupied[i].second + 1 - s);
if (dist < val) {
nearest = occupied[i].second + 1;
val = dist;
}
}
}
cout << nearest;
}
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 | #include <iostream> #include <algorithm> #include <vector> #include <climits> using namespace std; bool pairComp(const pair<int, int>& a, const pair<int, int>& b) { return a.first < b.first; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n; int m; int s; cin >> n >> m >> s; vector<pair<int, int>> occupied; int a, b; for (int i = 0; i < m; i++) { cin >> a >> b; occupied.push_back({ a, b }); } sort(occupied.begin(), occupied.end(), pairComp); occupied.insert(occupied.begin(), { -1, 0 }); occupied.push_back({ n + 1, n + 2 }); int nearest = -1; int val = INT_MAX; for (int i = 1; i < m + 1; i++) { if (occupied[i-1].second != occupied[i].first - 1) { int dist = abs(occupied[i].first - 1 - s); if (dist < val) { nearest = occupied[i].first - 1; val = dist; } } if (occupied[i].second + 1 != occupied[i + 1].first) { int dist = abs(occupied[i].second + 1 - s); if (dist < val) { nearest = occupied[i].second + 1; val = dist; } } } cout << nearest; } |
English