题解:AT_abc462_d [ABC462D] Accomplice
update:修正了对于难度的表述。
请注意,本题解使用的算法难度为
首先,我们可以枚举区间,然后问题转化为有多少个犯罪嫌疑人在这段时间里都在公寓里。
设我们枚举的区间为
具体实现的时候不需要把查询的区间插到所有区间里面去,可以对所有的犯罪嫌疑人按照
代码:
#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;
}