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;
}
全部评论

相关推荐

11-24 11:23
门头沟学院 C++
点赞 评论 收藏
分享
10-11 17:30
湖南大学 C++
我已成为0offer的糕手:羡慕
点赞 评论 收藏
分享
沉淀一会:1.同学你面试评价不错,概率很大,请耐心等待; 2.你的排名比较靠前,不要担心,耐心等待; 3.问题不大,正在审批,不要着急签其他公司,等等我们! 4.预计9月中下旬,安心过节; 5.下周会有结果,请耐心等待下; 6.可能国庆节前后,一有结果我马上通知你; 7.预计10月中旬,再坚持一下; 8.正在走流程,就这两天了; 9.同学,结果我也不知道,你如果查到了也告诉我一声; 10.同学你出线不明朗,建议签其他公司保底! 11.同学你找了哪些公司,我也在找工作。
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务