Powerful array
题目
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)
题目大意
给出n个数,m组询问,每组询问给出一段区间,输出区间内每个位置的val和,val的定义为该位置的数的值乘该位置上的数在区间内出现过的次数的平方。
思路
莫队板子题,对每个区间的数进行扫过去暴力维护
主要是没怎么写过莫队,或者说没怎么写出过莫队
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1e6+100;
struct Query {
int l,r,id,pos;
bool operator<(const Query &x)const {
if(pos!=x.pos)return pos<x.pos;
return r<x.r;
//return (pos^x.pos)?pos<x.pos:(pos&1)?r<x.r:r>x.r;//奇偶优化
}
} a[N];
ll b[N];
ll cnt[N],Ans[N];
ll ans=0;
void add(ll x) {
ans-=cnt[x]*cnt[x]*x;
cnt[x]++;
ans+=cnt[x]*cnt[x]*x;
}
void del(ll x) {
ans-=cnt[x]*cnt[x]*x;
cnt[x]--;
ans+=cnt[x]*cnt[x]*x;
}
void solve() {
int n,m;
cin>>n>>m;
int siz=sqrt(n);
for(int i=1; i<=n; i++)cin>>b[i];
for(int i=1; i<=m; i++) {
cin>>a[i].l>>a[i].r;
a[i].pos=(a[i].l-1)/siz+1;
a[i].id=i;
}
sort(a+1,a+m+1);
int l=1,r=0;
for(int i=1; i<=m; i++) {
while(l>a[i].l) {
l--;
add(b[l]);
}
while(r<a[i].r) {
r++;
add(b[r]);
}
while(l<a[i].l) {
del(b[l]);
l++;
}
while(r>a[i].r) {
del(b[r]);
r--;
}
Ans[a[i].id]=ans;
}
for(int i=1; i<=m; i++) {
cout<<Ans[i]<<'\n';
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
solve();
return 0;
}