莫队模板(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

Hint

题目大意:给出长度为n的数列,m次查询,每次查询求出区间 [ l ,r ] 内相同数字出现次数的立方的和。

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#include<algorithm>
#include<iostream>
using namespace std;
const int N=200010;
typedef long long ll;
int a[N],e[N],k;
ll ans,b[N],c[N];
struct node
{
    
    
	int l,r,id,pos;
} q[N];
bool cmp(node a,node b)
{
    
    
	if(a.pos==b.pos)
		return a.r<b.r;
	return a.pos<b.pos;
}
void update(int x,int p)
{
    
    
	if(x==0)
		return ;
	//printf("%d  %d\n",x,p);
	ans-=c[a[x]]*c[a[x]]*c[a[x]];
	//printf("%d**\n",ans);
	c[a[x]]+=p;
	//printf("%d****\n",c[a[x]]);
	ans+=c[a[x]]*c[a[x]]*c[a[x]];
	//printf("%d********\n",ans);
}
int main()
{
    
    
	int n,m,i;
	while(~scanf("%d",&n))
	{
    
    
		int p=sqrt(n*1.0);
		for(i=1; i<=n; i++)
		{
    
    
			scanf("%d",&a[i]);
			e[i]=a[i];
			c[i]=0;
		}
		//由于数字太大,所以进行离散化处理


		sort(e+1,e+1+n);
		k=unique(e+1,e+n+1)-(e+1);
		for(i=1; i<=n; i++)
			a[i]=lower_bound(e+1,e+1+k,a[i])-e;


		/*for(int i=1;i<=n;i++)
		{
			printf("%d ** ",a[i]);
		}
		printf("\n\n");*/
		scanf("%d",&m);
		for(i=0; i<m; i++)
		{
    
    
			scanf("%d%d",&q[i].l,&q[i].r);
			q[i].id=i;
			q[i].pos=q[i].l/p;
		}
		sort(q,q+m,cmp);
		int l=0,r=0;
		ans=0;
		for(i=0; i<m; i++)
		{
    
    
			while(l<q[i].l)
				update(l++,-1);
			while(l>q[i].l)
				update(--l,1);
			while(r>q[i].r)
				update(r--,-1);
			while(r<q[i].r)
				update(++r,1);
			b[q[i].id]=ans;
		}
		for(i=0; i<m; i++)
			printf("%lld\n",b[i]);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/zlzqq/article/details/114901492
今日推荐