A.Jujubesister
ac代码:
#include <algorithm>
#include <cmath>
#include <cstdio>
using namespace std;
typedef long long ll;
const int N = 1e6+10;
const int M = 1e6+10;
int n, m, maxn;
int c[M],cnt[M],b[N],a[N];
ll sum[N],ans,Ans[M];
struct query {
int l, r, id;
bool operator<(const query &x) const {
if (l / maxn != x.l / maxn) return l < x.l;
return (l / maxn) & 1 ? r < x.r : r > x.r;
}
} q[M];
void addl(int i) {
ans+=sum[a[i]]-(ll)cnt[a[i]]*b[i];
cnt[a[i]]++,sum[a[i]]+=b[i];
}
void dell(int i) {
cnt[a[i]]--,sum[a[i]]-=b[i];
ans-=sum[a[i]]-(ll)b[i]*cnt[a[i]];
}
void addr(int i) {
ans+=(ll)cnt[a[i]]*b[i]-sum[a[i]];
cnt[a[i]]++,sum[a[i]]+=b[i];
}
void delr(int i) {
cnt[a[i]]--,sum[a[i]]-=b[i];
ans-=(ll)b[i]*cnt[a[i]]-sum[a[i]];
}
int query(int i) {
int w=0;
for(; i; i-=i&-i) {
w+=c[i];
}
return w;
}
void add(int i) {
for( ; i<=n; i+=i&-i)c[i]++;
}
int main() {
scanf("%d%d", &n,&m);
maxn = sqrt(n);
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
b[i]=query(a[i]-1);
add(a[i]);
}
for (int i = 0; i < m; i++) scanf("%d%d", &q[i].l, &q[i].r), q[i].id = i;
sort(q, q + m);
for (int i = 0, l = 1, r = 0; i < m; i++) {
while (l > q[i].l) addl(--l);
while (r < q[i].r) addr(++r);
while (l < q[i].l) dell(l++);
while (r > q[i].r) delr(r--);
Ans[q[i].id] = ans;
}
for (int i = 0; i < m; i++) {
printf("%lld\n", Ans[i]);
}
return 0;
}