|
| 1 | +#include <iostream> |
| 2 | +#include <vector> |
| 3 | +#include <algorithm> |
| 4 | +#include <set> |
| 5 | + |
| 6 | +using namespace std; |
| 7 | + |
| 8 | +void solve() |
| 9 | +{ |
| 10 | + int no_of_elements; |
| 11 | + cin >> no_of_elements; |
| 12 | + |
| 13 | + vector <int> A(no_of_elements + 1), B(no_of_elements + 1); |
| 14 | + for(int i = 1; i <= no_of_elements; i++) |
| 15 | + { |
| 16 | + cin >> A[i] >> B[i]; |
| 17 | + } |
| 18 | + |
| 19 | + vector <pair <int, int> > prices (no_of_elements + 1); |
| 20 | + for(int i = 1; i <= no_of_elements; i++) |
| 21 | + { |
| 22 | + prices[i].first = A[i]; |
| 23 | + prices[i].second = B[i]; |
| 24 | + } |
| 25 | + |
| 26 | + sort(prices.begin() + 1, prices.end()); |
| 27 | + reverse(prices.begin() + 1, prices.end()); |
| 28 | + |
| 29 | + vector <int> prefix_max(no_of_elements + 1); |
| 30 | + for(int i = 1; i <= no_of_elements; i++) |
| 31 | + { |
| 32 | + prefix_max[i] = max(prefix_max[i - 1], prices[i].second); |
| 33 | + } |
| 34 | + |
| 35 | + const int oo = 2e9 + 9; |
| 36 | + int answer = oo; |
| 37 | + set <int> suffix; |
| 38 | + vector <int> suffix_next_greater(no_of_elements + 1, oo), suffix_next_lesser(no_of_elements + 1, oo); |
| 39 | + for(int i = no_of_elements; i >= 1; i--) |
| 40 | + { |
| 41 | + auto it = suffix.lower_bound(prices[i].first); |
| 42 | + |
| 43 | + if(it != suffix.end()) |
| 44 | + { |
| 45 | + suffix_next_greater[i] = *it; |
| 46 | + } |
| 47 | + |
| 48 | + if(it != suffix.begin()) |
| 49 | + { |
| 50 | + it--; |
| 51 | + } |
| 52 | + suffix_next_lesser[i] = *it; |
| 53 | + |
| 54 | + suffix.insert(prices[i].second); |
| 55 | + } |
| 56 | + |
| 57 | + for(int i = no_of_elements; i >= 1; i--) |
| 58 | + { |
| 59 | + int answer_here = oo; |
| 60 | + |
| 61 | + if(i > 1) |
| 62 | + { |
| 63 | + answer_here = abs(prices[i].first - prefix_max[i - 1]); |
| 64 | + } |
| 65 | + |
| 66 | + if(suffix_next_greater[i] >= prefix_max[i - 1]) |
| 67 | + { |
| 68 | + answer_here = min(answer_here, abs(prices[i].first - suffix_next_greater[i])); |
| 69 | + } |
| 70 | + |
| 71 | + if(suffix_next_lesser[i] >= prefix_max[i - 1]) |
| 72 | + { |
| 73 | + answer_here = min(answer_here, abs(prices[i].first - suffix_next_lesser[i])); |
| 74 | + } |
| 75 | + |
| 76 | + answer = min(answer, answer_here); |
| 77 | + } |
| 78 | + |
| 79 | + cout << answer << "\n"; |
| 80 | +} |
| 81 | + |
| 82 | +int main() |
| 83 | +{ |
| 84 | + int no_of_test_cases; |
| 85 | + cin >> no_of_test_cases; |
| 86 | + |
| 87 | + while(no_of_test_cases--) |
| 88 | + solve(); |
| 89 | + |
| 90 | + return 0; |
| 91 | +} |
| 92 | + |
| 93 | + |
0 commit comments