题意及思路:https://blog.csdn.net/tianyizhicheng/article/details/90369491
代码:
#include <bits/stdc++.h>
#define lowbit(x) (x & (-x))
using namespace std;
const int maxn = 30010;
int c[maxn * 3], num[maxn], b[maxn * 3], lb[maxn], rb[maxn], a[maxn];
int ans[maxn], tot;
struct Query {
int l, r, id;
bool operator < (const Query& rhs) const {
if(num[l] == num[rhs.l]) return r < rhs.r;
return num[l] < num[rhs.l];
}
};
Query q[maxn];
void add(int x, int y) {
for (; x <= tot; x += lowbit(x)) {
c[x] += y;
}
}
int query(int x) {
int ans = 0;
for (; x; x -= lowbit(x)) {
ans += c[x];
}
return ans;
}
int main() {
int n, m, k;
scanf("%d%d%d", &n, &m, &k);
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
b[++tot] = a[i], b[++tot] = a[i] + k, b[++tot] = a[i] - k - 1;
}
sort(b + 1, b + 1 + tot);
tot = unique(b + 1, b + 1 + tot) - (b + 1);
for (int i = 1; i <= n; i++) {
lb[i] = lower_bound(b + 1, b + 1 + tot, a[i] - k - 1) - b;
rb[i] = lower_bound(b + 1, b + 1 + tot, a[i] + k) - b;
a[i] = lower_bound(b + 1, b + 1 + tot, a[i]) - b;
}
for (int i = 1; i <= m; i++) {
scanf("%d%d", &q[i].l, &q[i].r);
q[i].id = i;
}
int len = sqrt(n);
for (int i = 1; i <= n; i++) {
num[i] = (i - 1) / len + 1;
}
sort(q + 1, q + 1 + m);
int l = q[1].l, r = q[1].l - 1, sum = 0;
for (int i = 1; i <= m; i++) {
while(r < q[i].r) {
r++;
sum += query(rb[r]) - query(lb[r]);
add(a[r], 1);
}
while(l > q[i].l) {
l--;
sum += query(rb[l]) - query(lb[l]);
add(a[l], 1);
}
while(r > q[i].r) {
add(a[r], -1);
sum -= query(rb[r]) - query(lb[r]);
r--;
}
while(l < q[i].l) {
add(a[l], -1);
sum -= query(rb[l]) - query(lb[l]);
l++;
}
ans[q[i].id] = sum;
}
for (int i = 1; i <= m; i++)
printf("%d\n", ans[i]);
}