Topic Links:
D. Powerful array
Time limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output
An array of positive integersa1,a2,...,aNis given. Let us consider its arbitrary subarraya l , a l + 1 ..., a R , Where 1≤ l ≤ r ≤ n . For every positive integer s denote by K s the number of occurrences Of s into the Subarray. We call The power of the Subarray the sum of Products K s · K s · 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 integers n and t (1≤ n, t ≤200000)-the array L Ength and the number of queries correspondingly.
Second Line contains n positive integers ai (1≤ a C18>i ≤106)-the elements of the array.
Next t lines contain-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 p Ower of the i-th query subarray.
%lld specificator to read or write 64-bit integers in C + +. It is a preferred to use cout stream (also).
Examplesinput
3 2
1 2 1
1 2
1 3
Output
3
6
Input
8 3
1 1 2 2 1 3 1 1
2 7
1 6
2 7
Output
20
20
20
Note
Consider the following array (see the second sample) and its [2, 7] Subarray (elements of the Subarray is colored):
Then
k1 = 3,
k2 = 2,
k3 = 1, so the power was equal to 32 1 + 2 2 2 + 12·3 =. AC Code:
#include <bits/stdc++.h>using namespacestd;Const intn=1e6+4;intn,t;Long LongA[n],num[n],ans[n];structnode{/*friend bool operator< () {}*/ intL,r,id,pos;}; Node Qu[n];intCMP (node X,node y) {if(X.pos==y.pos)returnx.r<Y.R; returnx.l<Y.L;}voidsolve () {Long Longtemp=0; intle=1, ri=0; for(intI=1; i<=t;i++) { while(ri<QU[I].R) {RI++; Temp+ = ((num[a[ri]]<<1)+1)*A[ri]; Num[a[ri]]++; } while(ri>QU[I].R) {Num[a[ri]]--; Temp-= ((num[a[ri]]<<1)+1)*A[ri]; RI--; } while(le<QU[I].L) {Num[a[le]]--; Temp-= ((num[a[le]]<<1)+1)*A[le]; Le++; } while(le>QU[I].L) {Le--; Temp+ = ((num[a[le]]<<1)+1)*A[le]; Num[a[le]]++; } Ans[qu[i].id]=temp; }}intMain () {scanf ("%d%d",&n,&t); for(intI=1; i<=n;i++) {scanf ("%i64d",&A[i]); } intsq=sqrt (n); for(intI=1; i<=t;i++) {scanf ("%d%d",&qu[i].l,&QU[I].R); Qu[i].id=i; Qu[i].pos=qu[i].l/sq; } sort (Qu+1, qu+t+1, CMP); Solve (); for(intI=1; i<=t;i++) {printf ("%i64d\n", Ans[i]); } return 0;}
Codeforces 86D D. Powerful Array (Mo team algorithm)