HDU6534 权值树状数组+莫队 Chika and Friendly Pairs
嘛,写完这道题后最莫队和树状数组的理解更进了一步
嘛,有关莫队的知识,请参考我的另一篇博客,莫队基本上写完一两道模板题后就基本理解了,很简单的
这次学到了一个很实用的STL 函数 unique函数,对于权值离散化非常有用,在对一个数组排完序以后,unique函数能够将相邻的重复元素,变成一个元素,将多余的元素放在结尾,然后查询位置时,我们直接用lower_bounder或upper_bounder查询就可以了
w[i] 保存每一个a[i]的位置,l[i] r[i] 分别保存 a[i]-k 和 a[i]+k 的位置
树状数组存的是数字加入区间的个数
特别注意分块排序,我在第二次写莫队的时候就没注意到,它是怎么比较的注意看清楚
不多说了,上代码
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn=27001;
int n,m,k,b,zans=0,ans[maxn],c[maxn],l[maxn],r[maxn];
int a[maxn],tmp[maxn];
int pos[maxn],w[maxn];
struct problem{
int l,r,id;
bool operator < (const problem &x)const{return pos[l]==pos[x.l] ? r<x.r : l<x.l;}
}pro[maxn];
void pre(){
sort(tmp+1,tmp+1+n);
unique(tmp+1,tmp+1+n)-(tmp+1);
for(int i=1;i<=n;i++){
w[i]=lower_bound(tmp+1,tmp+1+n,a[i])-tmp;//自己本身的位置
l[i]=lower_bound(tmp+1,tmp+1+n,a[i]-k)-tmp;//下边界位置
r[i]=upper_bound(tmp+1,tmp+1+n,a[i]+k)-tmp-1;//上边界位置
}
}
int getans(int x1,int x2){
int ans1=0,ans2=0;
x1--;//注意下边界要-1
while(x1){
ans1+=c[x1];
x1-=x1&-x1;
}
while(x2){
ans2+=c[x2];
x2-=x2&-x2;
}
return ans2-ans1;
}
void update(int x,int num){
while(x<maxn){
c[x]+=num;
x+=x&-x;
}
}
void add(int x){
zans+=getans(l[x],r[x]);
update(w[x],1);
}
void del(int x){
update(w[x],-1);
zans-=getans(l[x],r[x]);
}
int main(){
scanf("%d %d %d",&n,&m,&k);
fill(ans+1,ans+1+m,0);
b=sqrt(n);
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
tmp[i]=a[i];
pos[i]=i/b;
}
pre();
for(int i=1;i<=m;i++){
scanf("%d %d",&pro[i].l,&pro[i].r);
pro[i].id=i;
}
sort(pro+1,pro+1+m);
int le=1,ri=0;
for(int i=1;i<=m;i++){
while(le<pro[i].l)
del(le++);
while(le>pro[i].l)
add(--le);
while(ri>pro[i].r)
del(ri--);
while(ri<pro[i].r)
add(++ri);
ans[pro[i].id]=zans;
}
for(int i=1;i<=m;i++)
printf("%d\n",ans[i]);
return 0;
}
//权值树妆数组+莫队