http://acm.hdu.edu.cn/showproblem.php?pid=6534
题意:l,r区间内差值小于k的对数
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 27005;
int n,m,k;
int a[maxn];
int b[maxn];
int len;
struct node{
int l,r;
int x;
int id;
int ans;
bool operator<(const node &a) const {
if (l / len == a.l / len)
return (l / len) & 1 ? r < a.r : r > a.r;
return l / len < a.l / len;
}
} c[maxn];
int pos[maxn];
int d[maxn];
vector<int> v;
int ans;
int nn;
bool cmp1(node x,node y){
if(pos[x.l]==pos[y.l])
{
if(x.r<y.r)
return true;
return false;
}
if(x.l<y.l)
return true;
return false;
}
bool cmp2(node x,node y){
return x.id<y.id;
}
int lowbit(int x)
{
return x&(-x);
}
int Query(int x)
{
int aa = 0 ;
while(x)
{
aa += d[x];
x -= lowbit(x);
}
return aa;
}
void add(int x ,int value)
{
int tnt = a[x]+k;
int tnc = upper_bound(v.begin(),v.end(),tnt)-v.begin()-1;
int cnt = max(a[x]-k,0);
int cnc;
if(cnt!=0)
cnc = lower_bound(v.begin(),v.end(),cnt)-v.begin()-1;
else
cnc = 0;
ans += Query(tnc)-Query(cnc);
// cout<<Query(tnc)<<" "<<Query(cnc)<<endl;
// cout<<tnt<<" "<<cnt<<" "<<tnc<<" "<<cnc<<" "<<ans<<endl;
x = b[x];
while(x<=nn)
{
d[x] += value;
x += lowbit(x);
}
}
void remove(int x ,int value)
{
int tnt = a[x]+k;
int tnc = upper_bound(v.begin(),v.end(),tnt)-v.begin()-1;
int cnt = max(a[x]-k,0);
int cnc;
if(cnt!=0)
cnc = lower_bound(v.begin(),v.end(),cnt)-v.begin()-1;
else
cnc = 0;
ans -= Query(tnc)-Query(cnc)-1;
// cout<<Query(tnc)<<" "<<Query(cnc)<<endl;
// cout<<tnt<<" "<<cnt<<" "<<tnc<<" "<<cnc<<" "<<ans<<endl;
x = b[x];
// cout<<d[x]<<endl;
while(x<=nn)
{
d[x] += value;
// cout<<d[x]<<endl;
x += lowbit(x);
}
}
int main()
{
cin>>n>>m>>k;
memset(d,0,sizeof(d));
v.push_back(0);
for(int i=1;i<=n;i++)
cin>>a[i],v.push_back(a[i]);
sort(v.begin(),v.end());
v.erase(unique(v.begin(),v.end()),v.end());
nn = v.size();
for(int i=1;i<=n;i++)
b[i] = lower_bound(v.begin(),v.end(),a[i])-v.begin();
for(int i=1;i<=m;i++)
{
cin>>c[i].l>>c[i].r;
c[i].x = i;
c[i].id = i;
}
len = sqrt(n);
for(int i=1;i<=m;i++)
pos[i] = (i-1)/len + 1;
sort(c+1,c+1+m);
// cout<<endl;
// for(int i=1;i<=m;i++)
// cout<<c[i].l<<" "<<c[i].r<<endl;
// cout<<endl;
int l = 1,r = 0 ;
ans = 0;
for(int i=1;i<=m;i++)
{
while(r<c[i].r)
{
r++;
add(r,1);
}
while(r>c[i].r)
{
remove(r,-1);
r--;
}
while(l<c[i].l)
{
remove(l,-1);
l++;
}
while(l>c[i].l)
{
l--;
add(l,1);
}
c[i].ans = ans;
}
sort(c+1,c+1+m,cmp2);
for(int i=1;i<=m;i++)
cout<<c[i].ans<<endl;
return 0;
}