HDU6534 Chika and Friendly Pairs
树状数组 + 莫队
现场赛的时候树套树和主席树都没写出来TAT,比完发现正解是莫队。。
思路比较简洁,化简一下不等式,可以发现对于每个值x,实际上是找[x-k-1...x+k]范围内的数有多少个。
所以我们把所有数统统塞进树状数组,然后莫队暴力找就行啦。
注意一下每一个pair都不能算上自己,所以在区间增加时,应先维护答案,再维护树状数组,区间减少时,先维护树状数组,再统计答案。
#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
#define full(a, b) memset(a, b, sizeof a)
using namespace std;
typedef long long ll;
inline int lowbit(int x){ return x & (-x); }
inline int read(){
int X = 0, w = 0; char ch = 0;
while(!isdigit(ch)) { w |= ch == '-'; ch = getchar(); }
while(isdigit(ch)) X = (X << 3) + (X << 1) + (ch ^ 48), ch = getchar();
return w ? -X : X;
}
inline int gcd(int a, int b){ return b ? gcd(b, a % b) : a; }
inline int lcm(int a, int b){ return a / gcd(a, b) * b; }
template<typename T>
inline T max(T x, T y, T z){ return max(max(x, y), z); }
template<typename T>
inline T min(T x, T y, T z){ return min(min(x, y), z); }
template<typename A, typename B, typename C>
inline A fpow(A x, B p, C lyd){
A ans = 1;
for(; p; p >>= 1, x = 1LL * x * x % lyd)if(p & 1)ans = 1LL * x * ans % lyd;
return ans;
}
const int N = 30005;
int n, m, k, tot;
int a[N], b[3*N], lt[N], rt[N], tree[3*N], ans, res[N];
struct Query{
int l, r, block, id;
bool operator < (const Query &rhs) const {
return (block ^ rhs.block) ? l < rhs.l : (block & 1) ? r < rhs.r : r > rhs.r;
}
}query[N];
void add(int index, int i){
for(; index <= 3 * n; index += lowbit(index))
tree[index] += i;
}
int response(int index){
int ret = 0;
for(; index; index -= lowbit(index))
ret += tree[index];
return ret;
}
int main(){
n = read(), m = read(), k = read();
for(int i = 1; i <= n; i ++){
a[i] = read();
b[++tot] = a[i], b[++tot] = a[i] + k, b[++tot] = a[i] - k;
}
sort(b + 1, b + tot + 1);
tot = (int)(unique(b + 1, b + tot + 1) - b - 1);
for(int i = 1; i <= n; i ++){
lt[i] = (int)(lower_bound(b + 1, b + tot + 1, a[i] - k) - b);
rt[i] = (int)(lower_bound(b + 1, b + tot + 1, a[i] + k) - b);
a[i] = (int)(lower_bound(b + 1, b + tot + 1, a[i]) - b);
}
int t = (int)sqrt(n);
for(int i = 1; i <= m; i ++){
query[i].l = read(), query[i].r = read();
query[i].id = i, query[i].block = (query[i].l - 1) / t + 1;
}
sort(query + 1, query + m + 1);
int l = 1, r = 0;
for(int i = 1; i <= m; i ++){
int curL = query[i].l, curR = query[i].r;
while(r < curR){
r ++;
ans += response(rt[r]) - response(lt[r] - 1);
add(a[r], 1);
}
while(l > curL){
l --;
ans += response(rt[l]) - response(lt[l] - 1);
add(a[l], 1);
}
while(r > curR){
add(a[r], -1);
ans -= response(rt[r]) - response(lt[r] - 1);
r --;
}
while(l < curL){
add(a[l], -1);
ans -= response(rt[l]) - response(lt[l] - 1);
l ++;
}
res[query[i].id] = ans;
}
for(int i = 1; i <= m; i ++){
printf("%d\n", res[i]);
}
return 0;
}