请注意,本题解使用的算法难度为 ,并不是本题最简单的解法。
首先,我们可以枚举区间,然后问题转化为有多少个犯罪嫌疑人在这段时间里都在公寓里。
设我们枚举的区间为 ,那么包含它的区间 必定满足:。这是一个标准的二维偏序。使用 CDQ 分治或者树状数组求二维偏序都可以,我的代码采用树状数组实现。
具体实现的时候不需要把查询的区间插到所有区间里面去,可以对所有的犯罪嫌疑人按照 为第一关键字排序,然后在枚举的时候使用一个指针维护 。把前面的所有数字扔进一个权值树状数组里,然后每一次查询区间 有多少个数字就可以了。
代码:
#include<bits/stdc++.h>
#define int long long
#define endl '\n'
using namespace std;
namespace DS {
template<int N>
class FenwickTree {
protected:
int t[N], n;
inline int lowbit(int x) { return x & -x; }
public:
void init(int n) { this -> n = n; }
void update(int x, int v) {
for(; x <= n; x += lowbit(x)) t[x] += v;
}
int query(int x) {
int res = 0;
for(; x; x -= lowbit(x)) res += t[x];
return res;
}
int query(int l, int r) { return query(r) - query(l - 1); }
};
}
const int N = 1e6 + 5;
struct Node { int s, t; } c[N];
bool cmp(Node a, Node b) { return a.s < b.s; }
int pos, ans = 0, n, d;
DS::FenwickTree<N> T;
signed main() {
ios :: sync_with_stdio(0);
cin.tie(0), cout.tie(0);
cin >> n >> d;
T.init(1e6);
for(int i = 1; i <= n; i ++ ) { cin >> c[i].s >> c[i].t; }
sort(c + 1, c + n + 1, cmp);
for(int i = 1; i <= 1e6 - d; i ++ ) {
while(pos < n && c[pos + 1].s <= i) pos ++, T.update(c[pos].t, 1);
int c = T.query(i + d, 1e6);
ans += c * (c - 1) / 2;
}
cout << ans << endl;
return 0;
}