代码如下:
#include <bits/stdc++.h>
using namespace std;
const int NR = 1e5 + 10;
struct water
{
int x, t, id;
bool operator < (const water &o) const
{
return x < o.x;
}
} a[NR];
int n, d;
deque<int> q;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin >> n >> d;
for (int i = 1; i <= n; i++)
{
cin >> a[i].x >> a[i].t;
a[i].id = i;
}
sort(a + 1, a + n + 1);
int l = 1, r = 1, ans = 2e9;
q.push_front(1);
while (true)
{
while (!q.empty() && a[q.back()].t - a[q.front()].t >= d)
{
ans = min(ans, a[q.front()].x - a[q.back()].x);
l++;
while (!q.empty() && q.back() < l)
{
// cout << "Water[" << a[q.back()].id << "] is poped out." << endl;
q.pop_back();
}
}
if (r >= n) break;
bool flag = true;
while (q.empty() || a[q.back()].t - a[q.front()].t < d)
{
if (r >= n) break;
r++;
while (!q.empty() && a[r].t > a[q.front()].t)
{
// cout << "Water[" << a[q.front()].id << "] is poped out." << endl;
q.pop_front();
}
q.push_front(r);
// cout << "Water[" << a[q.front()].id << "] is pushed in." << endl;
}
if (r < n) ans = min(ans, a[r].x - a[l].x);
}
if (ans >= 1e9) cout << -1 << endl;
else cout << ans << endl;
return 0;
}