http://www.51nod.com/Challenge/Problem.html#problemId=1712
先考慮題面中的簡化問題。
對於\(i\in [1,n]\),\(a_i\)的貢獻爲\(a_i*(i-1)-a_i*(n-i)\)
那麼對於\(i\in [l,r](a_l=a_r)\),貢獻爲\(a_i*(i-l)-a_i*(r-i)=2i*a_i-a_i(l+r)\)
這個式子只須要統計4個東西就能夠\(O(n)\)計算了。html
那麼對答案的貢獻就是\(2*i*a_i*A*B-a_i*(BC+AD)\)
統計一下\(A,B,C,D\)便可。c++
#include <bits/stdc++.h> using namespace std; inline int read() { int x = 0, f = 1; char c = getchar(); while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();} while(c >= '0' && c <= '9') {x = x * 10 + c - '0'; c = getchar();} return x * f; } typedef unsigned int uint; const int N = 1000010; int n, lim, a[N]; uint num[N], sum[N], numl[N], numr[N], suml[N], sumr[N]; uint Sum, Num; int main() { n = read(); for(int i = 1; i <= n; ++i) { a[i] = read(); numr[a[i]]++; sumr[a[i]] += i; } uint ans = 0; for(int i = 1; i <= n; ++i) { numl[a[i]]++; suml[a[i]] += i; Num -= num[a[i]]; num[a[i]] = numl[a[i]] * numr[a[i]]; Num += num[a[i]]; Sum -= sum[a[i]]; sum[a[i]] = suml[a[i]] * numr[a[i]] + sumr[a[i]] * numl[a[i]]; Sum += sum[a[i]]; ans += 2 * i * a[i] * Num - a[i] * Sum; numr[a[i]]--; sumr[a[i]] -= i; Num -= num[a[i]]; num[a[i]] = numl[a[i]] * numr[a[i]]; Num += num[a[i]]; Sum -= sum[a[i]]; sum[a[i]] = suml[a[i]] * numr[a[i]] + sumr[a[i]] * numl[a[i]]; Sum += sum[a[i]]; } printf("%u\n", ans); }