#include <bits/stdc++.h>
using namespace std;
using ll = long long;
ll n; // liczba budynków
int m; // liczba przedziałów
ll s; // numer budynku, w którym jest szkoła
vector<pair<ll,ll>> intervals;
ll dist(ll x) {
return abs(x - s);
}
int main() {
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
cin >> n >> m >> s;
for (int i=0; i<m; i++) {
ll l, r;
cin >> l >> r;
intervals.push_back({ l, r });
}
sort(intervals.begin(), intervals.end());
int idx_s = 0;
for (int i=0; i<m; i++) {
const auto& [l, r] = intervals[i];
if (l <= s && s <= r) {
idx_s = i;
break;
}
}
int i = idx_s - 1;
ll ans_right = -1;
while (i < m) {
i++;
const auto& [l, r] = intervals[i];
if (i == m-1) {
if (r+1 <= n) {
ans_right = r + 1;
break;
}
}
else {
const auto& [l_, r_] = intervals[i+1];
if (r+1 < l_) {
ans_right = r + 1;
break;
}
}
}
i = idx_s + 1;
ll ans_left = -1;
while (i >= 0) {
i--;
const auto& [l, r] = intervals[i];
if (i == 0) {
if (1 < l) {
ans_left = l - 1;
break;
}
}
else {
const auto& [_l, _r] = intervals[i-1];
if (_r < l-1) {
ans_left = l - 1;
break;
}
}
}
if (ans_left != -1 && (dist(ans_left) <= dist(ans_right) || ans_right == -1)) {
cout << ans_left << "\n";
}
else {
cout << ans_right << "\n";
}
}
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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | #include <bits/stdc++.h> using namespace std; using ll = long long; ll n; // liczba budynków int m; // liczba przedziałów ll s; // numer budynku, w którym jest szkoła vector<pair<ll,ll>> intervals; ll dist(ll x) { return abs(x - s); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n >> m >> s; for (int i=0; i<m; i++) { ll l, r; cin >> l >> r; intervals.push_back({ l, r }); } sort(intervals.begin(), intervals.end()); int idx_s = 0; for (int i=0; i<m; i++) { const auto& [l, r] = intervals[i]; if (l <= s && s <= r) { idx_s = i; break; } } int i = idx_s - 1; ll ans_right = -1; while (i < m) { i++; const auto& [l, r] = intervals[i]; if (i == m-1) { if (r+1 <= n) { ans_right = r + 1; break; } } else { const auto& [l_, r_] = intervals[i+1]; if (r+1 < l_) { ans_right = r + 1; break; } } } i = idx_s + 1; ll ans_left = -1; while (i >= 0) { i--; const auto& [l, r] = intervals[i]; if (i == 0) { if (1 < l) { ans_left = l - 1; break; } } else { const auto& [_l, _r] = intervals[i-1]; if (_r < l-1) { ans_left = l - 1; break; } } } if (ans_left != -1 && (dist(ans_left) <= dist(ans_right) || ans_right == -1)) { cout << ans_left << "\n"; } else { cout << ans_right << "\n"; } } |
English