传送门:https://codeforces.com/contest/86/problem/D
题意:
给你n个数,m次询问,每次询问问你在区间l,r内每个数字出现的次数的平方于当前这个数的乘积的和
题解:
莫队算法
思路:
根据平方和公式我们知道
[(a+1)^2=a^2+2a+1
]
于是在记录每一次询问的答案时
add操作就是加上这个数的贡献
del操作就是减去这个数的贡献
每个数多出一次或者减少一次的对答案贡献就是
[a_i*(cnt[a[i]]*2+1)
]
代码:
/**
* ┏┓ ┏┓
* ┏┛┗━━━━━━━┛┗━━━┓
* ┃ ┃
* ┃ ━ ┃
* ┃ > < ┃
* ┃ ┃
* ┃... ⌒ ... ┃
* ┃ ┃
* ┗━┓ ┏━┛
* ┃ ┃ Code is far away from bug with the animal protecting
* ┃ ┃ 神兽保佑,代码无bug
* ┃ ┃
* ┃ ┃
* ┃ ┃
* ┃ ┃
* ┃ ┗━━━┓
* ┃ ┣┓
* ┃ ┏┛
* ┗┓┓┏━┳┓┏┛
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛
*/
// warm heart, wagging tail,and a smile just for you!
//
// _ooOoo_
// o8888888o
// 88" . "88
// (| -_- |)
// O = /O
// ____/`---'\____
// .' | |// `.
// / ||| : |||//
// / _||||| -:- |||||-
// | | \ - /// | |
// | \_| ''---/'' | |
// .-\__ `-` ___/-. /
// ___`. .' /--.-- `. . __
// ."" '< `.___\_<|>_/___.' >'"".
// | | : `- \`.;` _ /`;.`/ - ` : | |
// `-. \_ __ /__ _/ .-` / /
// ======`-.____`-.___\_____/___.-`____.-'======
// `=---='
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// 佛祖保佑 永无BUG
#include <set>
#include <map>
#include <deque>
#include <queue>
#include <stack>
#include <cmath>
#include <ctime>
#include <bitset>
#include <cstdio>
#include <string>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
typedef pair<LL, LL> pLL;
typedef pair<LL, int> pLi;
typedef pair<int, LL> pil;;
typedef pair<int, int> pii;
typedef unsigned long long uLL;
#define ls rt<<1
#define rs rt<<1|1
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define bug printf("*********
")
#define FIN freopen("input.txt","r",stdin);
#define FON freopen("output.txt","w+",stdout);
#define IO ios::sync_with_stdio(false),cin.tie(0)
#define debug1(x) cout<<"["<<#x<<" "<<(x)<<"]
"
#define debug2(x,y) cout<<"["<<#x<<" "<<(x)<<" "<<#y<<" "<<(y)<<"]
"
#define debug3(x,y,z) cout<<"["<<#x<<" "<<(x)<<" "<<#y<<" "<<(y)<<" "<<#z<<" "<<z<<"]
"
const double eps = 1e-8;
const int mod = 1e9 + 7;
const int maxn = 1e6 + 5;
const int INF = 0x3f3f3f3f;
const LL INFLL = 0x3f3f3f3f3f3f3f3f;
struct node {
int l, r, id;
} q[maxn];
int pos[maxn];
bool cmp(node a, node b) {
if(pos[a.l] == pos[b.l]) return a.r < b.r;
return pos[a.l] < pos[b.l]; 8
}
int a[maxn];
int cnt[maxn];
LL Ans;
void add(int x) {
Ans += (LL)a[x] * (cnt[a[x]] * 2 + 1); //(a+1)*(a+1)=a*a+2*a+1;
cnt[a[x]]++;
}
void del(int x) {
cnt[a[x]]--;
Ans -= (LL)a[x] * (cnt[a[x]] * 2 + 1);
}
LL ans[maxn];
int main() {
#ifndef ONLINE_JUDGE
FIN
#endif
int n, m;
scanf("%d%d", &n, &m);
int sz = sqrt(n);
for(int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
pos[i] = i / sz;
}
for(int i = 1; i <= m; i++) {
scanf("%d%d", &q[i].l, &q[i].r);
q[i].id = i;
}
sort(q + 1, q + m + 1, cmp);
int L = 1, R = 0;
Ans = 0;
for(int i = 1; i <= m; i++) {
while(L > q[i].l) {
add(--L);
}
while(L < q[i].l) {
del(L++);
}
while(R < q[i].r) {
add(++R);
}
while(R > q[i].r) {
del(R--);
}
ans[q[i].id] = Ans;
}
for(int i = 1; i <= m; i++) {
printf("%lld
", ans[i]);
}
return 0;
}