莫队,离线操作,不断将区间逼近所求区间,加减贡献值即可
AC代码:
#include<bits/stdc++.h>
using namespace std;
//莫队算法
const int maxn=1e5+5;
int pos[maxn],a[maxn],c[maxn];
long long ans[maxn],res;
struct node
{
int l,r,poi;
} q[maxn];
bool cmp(node x,node y)//排序可以减少复杂度
{
if(pos[x.l]==pos[y.l])
{
return x.r<y.r;
}
return pos[x.l]<pos[y.l];
}
void pushup(int x,int y)
{
a[x]-=y;
}
void add(int i)
{
// c[a[i]]++;
res+=a[i];
}
void sub(int i)
{
//c[a[i]]--;
res-=a[i];
}
int main()
{
int n,m,k;
scanf("%d",&n);
int dis=sqrt(n);
for(int i=1; i<=n; i++)
{
scanf("%d",&a[i]);
pos[i]=i/dis;
}
scanf("%d",&m);
for(int i=0; i<m; i++)
{
scanf("%d %d",&q[i].l,&q[i].r);
q[i].r=q[i].l+q[i].r-1;
q[i].poi=i;
}
sort(q,q+m,cmp);
int l=1,r=0;
for(int i=0; i<m; i++)
{
while(l<q[i].l)
{
sub(l++);
}
while(r>q[i].r)
{
sub(r--);
}
while(l>q[i].l)
{
add(--l);
}
while(r<q[i].r)
{
add(++r);
}
ans[q[i].poi]=res;
}
for(int i=0; i<m; i++)
{
printf("%lld\n",ans[i]);
}
}