1. 程式人生 > >分塊/莫隊演算法Codeforces86D

分塊/莫隊演算法Codeforces86D

題目連結:http://codeforces.com/contest/86/problem/D

#include <bits/stdc++.h>

using namespace std;
using ll = long long ;
const int N = 1E6 + 7;
int a[N], belong[N], BLOCK, sum[N];
ll res, ans[N];
struct node
{
    int l, r, id;
    bool operator < (const node & x) const {
        if(belong[l] == belong[x.l]) return r < x.r;
        else return l < x.l;
    }
}Q[N];
void modify(int p, int add)
{
    res -= a[p] * 1ll * sum[a[p]] * sum[a[p]];
    sum[a[p]] += add;
    res += a[p] * 1ll * sum[a[p]] * sum[a[p]];
}
int main()
{
    int n, t;
    scanf("%d%d",&n,&t);
    BLOCK = sqrt(n);
    for(int i = 1;i <= n;i ++) scanf("%d",&a[i]), belong[i] = (i - 1) / BLOCK + 1;
    for(int i = 1;i <= t;i ++) {
        scanf("%d%d",&Q[i].l,&Q[i].r);
        Q[i].id = i;
    }
    sort(Q+1, Q+1+t);
    for(int i = 1, l = 1, r = 0;i <= t;i ++) {
        for(;r < Q[i].r; r ++) modify(r+1, 1);
        for(;r > Q[i].r; r --) modify(r, -1);
        for(;l < Q[i].l; l ++) modify(l, -1);
        for(;l > Q[i].l; l --) modify(l-1, 1);
        ans[Q[i].id] = res;
    }
    for(int i = 1; i <= t; i ++) printf("%lld\n",ans[i]);
    return 0;
}