Sona(莫队+离散化)

Sona, Maven of the Strings. Of cause, she can play the zither.

Sona can’t speak but she can make fancy music. Her music can attack, heal, encourage and enchant.

There’re an ancient score(乐谱). But because it’s too long, Sona can’t play it in a short moment. So Sona decide to just play a part of it and revise it.

A score is composed of notes. There are 109 kinds of notes and a score has 105 notes at most.

To diversify Sona’s own score, she have to select several parts of it. The energy of each part is calculated like that:

Count the number of times that each notes appear. Sum each of the number of times’ cube together. And the sum is the energy.

You should help Sona to calculate out the energy of each part.

Input
This problem contains several cases. And this problem provides 2 seconds to run.
The first line of each case is an integer N (1 ≤ N ≤ 10^5), indicates the number of notes.
Then N numbers followed. Each number is a kind of note. (1 ≤ NOTE ≤ 10^9)
Next line is an integer Q (1 ≤ Q ≤ 10^5), indicates the number of parts.
Next Q parts followed. Each part contains 2 integers Li and Ri, indicates the left side of the part and the right side of the part.
Output
For each part, you should output the energy of that part.

Sample Input
8
1 1 3 1 3 1 3 3
4
1 8
3 8
5 6
5 5

Sample Output
128
72
2
1

题意: 给定N个数和m次查询,查询给定范围内不同种类颜色出现次数的立方和。

题解:莫队算法加离散化

代码如下

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
using namespace std;
long long a[200010],b[200010],c[200010];
long long sum,k,d[200010];
struct z{
	int l,r,id,p;
} s[200010];
bool cmp(z a,z b)   //对查询进行排序 
{
	if(a.p==b.p)
	return a.r<b.r;
	else
	return a.p<b.p;
}
void add(int x,int y)  //随着范围移动数据加减
{
	if(x==0)
	return ;
	sum=sum-c[a[x]]*c[a[x]]*c[a[x]];  //减去原来的
	c[a[x]]=c[a[x]]+y;
	sum=sum+c[a[x]]*c[a[x]]*c[a[x]];  //加上现在的
}
int main()
{
	int n,m;
	while(~scanf("%d",&n)&&n)
	{
		int i,j,l=0,r=0;
		for(i=1;i<=n;i++)
		{
			scanf("%lld",&a[i]);
			d[i]=a[i];
			c[i]=0;
		}
		scanf("%d",&m);
		sort(d+1,d+1+n);
		k=unique(d+1,d+n+1)-(d+1);
		for(i=1;i<=n;i++)
		a[i]=lower_bound(d+1,d+1+k,a[i])-d;   //离散化进行优化 
		int x=sqrt(n);
		for(i=0;i<m;i++)
		{
			scanf("%d%d",&s[i].l,&s[i].r);
			s[i].id=i;
			s[i].p=s[i].l/x;
		}
		sort(s,s+m,cmp);
		sum=0;
		for(i=0;i<m;i++)          //莫队 
		{
			while(l<s[i].l) add(l++,(-1));
			while(l>s[i].l) add(--l,1);
			while(r>s[i].r) add(r--,(-1));
			while(r<s[i].r) add(++r,1);
			b[s[i].id]=sum;
		}
		for(i=0;i<m;i++)
		printf("%lld\n",b[i]);
	}
	return 0;
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值