#include #include #include #include constexpr int INF = 0x3f3f3f3f; template class QueueWithMinMax : public std::queue { protected: std::deque min_queue; std::deque max_queue; public: using std::queue::queue; void push(T x) { while (!min_queue.empty() && min_queue.back() > x) { min_queue.pop_back(); } min_queue.push_back(x); while (!max_queue.empty() && max_queue.back() < x) { max_queue.pop_back(); } max_queue.push_back(x); std::queue::push(x); } void pop() { if (!min_queue.empty() && min_queue.front() == std::queue::front()) { min_queue.pop_front(); } if (!max_queue.empty() && max_queue.front() == std::queue::front()) { max_queue.pop_front(); } std::queue::pop(); } T get_max() { return max_queue.front(); } T get_min() { return min_queue.front(); } auto get_difference() -> decltype(get_max() - get_min()) { if (std::queue::empty()) { return -1; } return get_max() - get_min(); } }; using Range = std::pair; using Coord = std::pair; int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); int n, target_diff; std::vector coords; std::vector positions; std::map moments; // std::vector moments; std::cin >> n >> target_diff; coords.resize(n); for (int i = 0; i < n; i++) { // std::cin >> positions[i] >> temp; std::cin >> coords[i].first >> coords[i].second; } std::sort(coords.begin(), coords.end()); int ans = +INF, p1 = 0, p2 = 0; QueueWithMinMax queue; queue.push(coords[0].second); while (p2 < n) { if (queue.get_difference() < target_diff) { p2++; if (p2 < n) { queue.push(coords[p2].second); } } else { if (coords[p1].first == coords[p2].first) { ans = 0; break; } ans = std::min(ans, coords[p2].first - coords[p1].first); p1++; queue.pop(); } } if (ans == +INF) { ans = -1; } std::cout << ans << std::endl; return 0; }