Codeforces - D. Powerful array

D. Powerful array

time limit per test5 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
An array of positive integers a1, a2, …, an is given. Let us consider its arbitrary subarray al, al + 1…, ar, where 1 ≤ l ≤ r ≤ n. For every positive integer s denote by Ks the number of occurrences of s into the subarray. We call the power of the subarray the sum of products Ks·Ks·s for every positive integer s. The sum contains only finite number of nonzero summands as the number of different values in the array is indeed finite.

You should calculate the power of t given subarrays.

Input
First line contains two integers n and t (1 ≤ n, t ≤ 200000) — the array length and the number of queries correspondingly.

Second line contains n positive integers ai (1 ≤ ai ≤ 106) — the elements of the array.

Next t lines contain two positive integers l, r (1 ≤ l ≤ r ≤ n) each — the indices of the left and the right ends of the corresponding subarray.

Output
Output t lines, the i-th line of the output should contain single positive integer — the power of the i-th query subarray.

Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preferred to use cout stream (also you may use %I64d).

Examples
inputCopy
3 2
1 2 1
1 2
1 3
outputCopy
3
6
inputCopy
8 3
1 1 2 2 1 3 1 1
2 7
1 6
2 7
outputCopy
20
20
20
Note
Consider the following array (see the second sample) and its [2, 7] subarray (elements of the subarray are colored):


Then K1 = 3, K2 = 2, K3 = 1, so the power is equal to 32·1 + 22·2 + 12·3 = 20.


在那个莫队还没有的年代,这居然是2700分的题目?你敢信?

这道题直接莫队,维护每个数字出现的次数即可。


AC代码:

#pragma GCC optimize(2)
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=2e5+10;
int n,q,a[N],cnt[N*5],res[N],s,bl,cl=1,cr;
struct node{int id,l,r;}t[N];
int cmp(node a,node b){return a.l/bl==b.l/bl?a.r<b.r:a.l<b.l;}
inline void add(int x){s+=x*((cnt[x]<<1ll)+1);	++cnt[x];}
inline void del(int x){s-=x*((cnt[x]<<1ll)-1);	--cnt[x];}
signed main(){
	cin>>n>>q; bl=sqrt(n);
	for(int i=1;i<=n;i++)	scanf("%lld",&a[i]);
	for(int i=1;i<=q;i++)	scanf("%lld %lld",&t[i].l,&t[i].r),t[i].id=i;
	sort(t+1,t+1+q,cmp);
	for(int i=1;i<=q;i++){
		int L=t[i].l,R=t[i].r;
		while(cr<R)	add(a[++cr]);
		while(cl>L)	add(a[--cl]);
		while(cr>R)	del(a[cr--]);
		while(cl<L)	del(a[cl++]);
		res[t[i].id]=s;
	}
	for(int i=1;i<=q;i++)	printf("%lld\n",res[i]);
	return 0;
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
今天 17:23
点赞 评论 收藏
分享
06-17 21:57
门头沟学院 Java
白友:噗嗤,我发现有些人事就爱发这些,明明已读不回就行了,就是要恶心人
点赞 评论 收藏
分享
写不来代码的小黑:这么小的城市能有做it的公司也不容易
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务