题目链接:Sona - NBUT 1457 - Virtual Judge (ppsucxtt.cn)
题意比较简单:有N个数,有M个询问,求每次询问的区间[L,R]中,每种数字出现次数的立方和。
在之前做过了好几道类似的题目,没思路的小伙伴可以看下我之前的博客,之前在介绍莫队的时候用的例子就是有N个数,有M个询问,求每次询问的区间[L,R]中,每种数字出现次数的平方和,下面附上那篇博客地址:(39条消息) 莫队(离线处理区间询问)_AC__dream的博客-优快云博客
这道题目是求的每个数字出现次数的立方和,和那个平方和的题目没有太大差别,但是需要注意的是这道题目的数据范围比较大,我们无法直接开一个等大的数组来记录其出现次数,再一看数据范围,发现总的数目比较少,显然就是让我们用离散化来处理了,就是把原数变成其离散化后的数再进行莫队处理就行,处理方法与平方和的那道题没有什么差别,最后需要注意的就是这个题目是多组输入,不要忘记初始化,下面直接上代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<queue>
#include<vector>
#include<cmath>
using namespace std;
const int N=1e6+10;
#define int long long
struct node{
int l,r,pl,id;
}p[N];
bool cmp(node a,node b)
{
if(a.pl!=b.pl) return a.pl<b.pl;
return a.r<b.r;
}
int ans,sum[N],cnt[N],a[N];
vector<int> alls;
//离散化
int find(int x)
{
return lower_bound(alls.begin(),alls.end(),x)-alls.begin()+1;
}
void add(int x)
{
ans-=cnt[x]*cnt[x]*cnt[x];
cnt[x]++;
ans+=cnt[x]*cnt[x]*cnt[x];
}
void sub(int x)
{
ans-=cnt[x]*cnt[x]*cnt[x];
cnt[x]--;
ans+=cnt[x]*cnt[x]*cnt[x];
}
signed main()
{
int n,m;
while(scanf("%lld",&n)!=EOF)
{
int pl=1;
while(pl*pl<n) pl++;
alls.clear();//记得初始化
ans=0;
for(int i=1;i<=n;i++)
{
cnt[i]=0;
scanf("%lld",&a[i]);
alls.push_back(a[i]);
}
sort(alls.begin(),alls.end());
alls.erase(unique(alls.begin(),alls.end()),alls.end());
for(int i=1;i<=n;i++)
a[i]=find(a[i]);
scanf("%lld",&m);
for(int i=1;i<=m;i++)
{
scanf("%lld%lld",&p[i].l,&p[i].r);
p[i].id=i;
p[i].pl=(p[i].l-1)/pl+1;
}
sort(p+1,p+m+1,cmp);
int l=1,r=0;
for(int i=1;i<=m;i++)
{
while(l<p[i].l)
{
sub(a[l]);
l++;
}
while(l>p[i].l)
{
l--;
add(a[l]);
}
while(r<p[i].r)
{
r++;
add(a[r]);
}
while(r>p[i].r)
{
sub(a[r]);
r--;
}
sum[p[i].id]=ans;
}
for(int i=1;i<=m;i++)
printf("%lld\n",sum[i]);
}
return 0;
}
该博客介绍了如何使用离散化和莫队(单调队列)技术解决一个关于区间内数字立方和的查询问题。通过将数据范围压缩到较少的离散值,博主分享了解决大数范围查询的高效解决方案,并提供了详细的代码实现。
795





