#include <iostream> #include <vector> #include <algorithm> using namespace std; using ll = long long; typedef pair<ll, ll> pll; bool sort_operator(pll a, pll b) { return (a.second - a.first) < (b.second - b.first); } ll cal_best(vector<pll>& ranges, ll n, ll s) { sort(ranges.begin(), ranges.end(), sort_operator); ll candi1 = s - 1; bool ch = true; while(ch && candi1 >= 1) { ch = false; for(ll i = 0; i < ranges.size(); i++) { if (ranges[i].first <= candi1 && candi1 <= ranges[i].second) { ch = true; candi1 = ranges[i].first - 1; break; } } } ll candi2 = s + 1; ch = true; while(ch && candi2 <= n) { ch = false; for(ll i = 0; i < ranges.size(); i++) { if (ranges[i].first <= candi2 && candi2 <= ranges[i].second) { ch = true; candi2 = ranges[i].second + 1; break; } } } if (candi1 < 1) return candi2; if (candi2 > n) return candi1; if(abs(s - candi1) <= abs(candi2 - s)) return candi1; else return candi2; } int main() { ll n, m, s; cin >> n >> m >> s; vector<pll> ranges(m); for (ll i = 0; i < m; i++) { cin >> ranges[i].first >> ranges[i].second; } cout << cal_best(ranges, n, s) << "\n"; return 0; }
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 | #include <iostream> #include <vector> #include <algorithm> using namespace std; using ll = long long; typedef pair<ll, ll> pll; bool sort_operator(pll a, pll b) { return (a.second - a.first) < (b.second - b.first); } ll cal_best(vector<pll>& ranges, ll n, ll s) { sort(ranges.begin(), ranges.end(), sort_operator); ll candi1 = s - 1; bool ch = true; while(ch && candi1 >= 1) { ch = false; for(ll i = 0; i < ranges.size(); i++) { if (ranges[i].first <= candi1 && candi1 <= ranges[i].second) { ch = true; candi1 = ranges[i].first - 1; break; } } } ll candi2 = s + 1; ch = true; while(ch && candi2 <= n) { ch = false; for(ll i = 0; i < ranges.size(); i++) { if (ranges[i].first <= candi2 && candi2 <= ranges[i].second) { ch = true; candi2 = ranges[i].second + 1; break; } } } if (candi1 < 1) return candi2; if (candi2 > n) return candi1; if(abs(s - candi1) <= abs(candi2 - s)) return candi1; else return candi2; } int main() { ll n, m, s; cin >> n >> m >> s; vector<pll> ranges(m); for (ll i = 0; i < m; i++) { cin >> ranges[i].first >> ranges[i].second; } cout << cal_best(ranges, n, s) << "\n"; return 0; } |