hdu 6534 Chika and Friendly Pairs(莫队+树状数组)
目录
题意
给你n个数,然后m个区间查询,求区间里满足|ai-aj|<=k的对数(L<=i<j<=R)
题解
求出每一个数与其能满足条件的数的范围在哪个区间,故将ai离散化,再将ai-k、ai+k离散化,然后直接莫队+树状数组求解
代码
#include<bits/stdc++.h>
using namespace std;
const int maxx = 27010;
struct node{int l,r,id,block;}q[maxx];
bool cmp(node a,node b)
{
if(a.block==b.block)return a.r<b.r;
return a.block<b.block;
}
int a[maxx],b[maxx],t[maxx],ll[maxx],rr[maxx];
int tree[maxx],res[maxx];
int n,m,k,s;
void add(int x,int c)
{
for(int i=x;i<=s;i+=(i&-i))
tree[i]+=c;
}
int getsum(int x)
{
int res=0;
for(int i=x;i>0;i-=(i&-i))
res+=tree[i];
return res;
}
int main()
{
while(~scanf("%d%d%d",&n,&m,&k))
{
for(int i=1;i<=n;i++)
{
scanf("%d",&t[i]);
b[i]=t[i];
tree[i]=0;
}
sort(b+1,b+1+n);
s=unique(b+1,b+1+n)-b-1;
for(int i=1;i<=n;i++)
{
a[i]=lower_bound(b+1,b+1+s,t[i])-b;
ll[i]=lower_bound(b+1,b+1+s,t[i]-k)-b;//找第一个大于或等于的位置
rr[i]=upper_bound(b+1,b+1+s,t[i]+k)-b-1;//找第一个大于的位置
//找不到返回end
}
int siz=sqrt(n);
for(int i=1;i<=m;i++)
{
scanf("%d%d",&q[i].l,&q[i].r);
q[i].id=i;
q[i].block=(q[i].l-1)/siz+1;
}
sort(q+1,q+1+m,cmp);
int l=1,r=0,ans=0;
for(int i=1;i<=m;i++)
{
while(l<q[i].l)add(a[l],-1),ans-=(getsum(rr[l])-getsum(ll[l]-1)),l++;
while(l>q[i].l)l--,ans+=(getsum(rr[l])-getsum(ll[l]-1)),add(a[l],1);
while(r<q[i].r)r++,ans+=(getsum(rr[r])-getsum(ll[r]-1)),add(a[r],1);
while(r>q[i].r)add(a[r],-1),ans-=(getsum(rr[r])-getsum(ll[r]-1)),r--;
res[q[i].id]=ans;
}
for(int i=1;i<=m;i++)
printf("%d\n",res[i]);
}
return 0;
}