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

题意:求区间内,每个数出现次数x的立方和。

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <math.h>
using namespace std;
const int maxn=1e6+10;
long long cnt[maxn];
long long res[maxn];
struct node{
	int L,R,id;
}q[maxn];
int pos[maxn];
int a[maxn],b[maxn];
long long ans;
bool cmp(node a,node b)
{
	if(pos[a.L]!=pos[b.L]) return pos[a.L]<pos[b.L];
	if(pos[a.L]&1) return a.R>b.R;
	return a.R<b.R;
}
void add(int x)
{
	ans-=cnt[a[x]]*cnt[a[x]]*cnt[a[x]];
	cnt[a[x]]++;
	ans+=cnt[a[x]]*cnt[a[x]]*cnt[a[x]];
}
void del(int x)
{
	ans-=cnt[a[x]]*cnt[a[x]]*cnt[a[x]];
	cnt[a[x]]--;
	ans+=cnt[a[x]]*cnt[a[x]]*cnt[a[x]];
}
int main()
{
	int n,m;
	while(~scanf("%d",&n)&&n)
	{
		ans=0;
		memset(q,0,sizeof(q));
		memset(res,0,sizeof(res));
		memset(cnt,0,sizeof(cnt));
		int block=n/sqrt(m);
		for(int i=1;i<=n;i++) 
		{
			scanf("%d",&a[i]);
			b[i]=a[i];
			pos[i]=(i-1)/block+1;
		}
		//离散化 
		sort(b+1,b+1+n);
		int len=unique(b+1,b+1+n)-b;
		for(int i=1;i<=n;i++)
			a[i]=lower_bound(b+1,b+1+len,a[i])-b;
		
		scanf("%d",&m);
		for(int i=1;i<=m;i++)
		{
			scanf("%d%d",&q[i].L,&q[i].R);
			q[i].id=i;
		}
		//莫队 
		sort(q+1,q+1+m,cmp);
		int l=1,r=0;
		for(int i=1;i<=m;i++)
		{
			while(l<q[i].L) del(l++);//减小区间,l右移
			while(r>q[i].R) del(r--);//减小区间,r左移 
			while(l>q[i].L) add(--l);//增加区间,l左移
			while(r<q[i].R) add(++r); 
			res[q[i].id]=ans;
		}
		for(int i=1;i<=m;i++) printf("%lld\n",res[i]);
	}
 } 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值