(NBUT - 1457)Sona(莫队+离散化)

题目链接:Sona - NBUT 1457 - Virtual Judge (ppsucxtt.cn)

题意比较简单:有N个数,有M个询问,求每次询问的区间[L,R]中,每种数字出现次数的立方和。

在之前做过了好几道类似的题目,没思路的小伙伴可以看下我之前的博客,之前在介绍莫队的时候用的例子就是有N个数,有M个询问,求每次询问的区间[L,R]中,每种数字出现次数的平方和,下面附上那篇博客地址:(39条消息) 莫队(离线处理区间询问)_AC__dream的博客-CSDN博客

这道题目是求的每个数字出现次数的立方和,和那个平方和的题目没有太大差别,但是需要注意的是这道题目的数据范围比较大,我们无法直接开一个等大的数组来记录其出现次数,再一看数据范围,发现总的数目比较少,显然就是让我们用离散化来处理了,就是把原数变成其离散化后的数再进行莫队处理就行,处理方法与平方和的那道题没有什么差别,最后需要注意的就是这个题目是多组输入,不要忘记初始化,下面直接上代码:

#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;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值