# ABC194 C - Squared Error（推式子）

#### 解法：

∑ i = 2 n ∑ j = 1 i − 1 ( a [ i ] − a [ j ] ) 2 = ∑ i = 2 n ∑ j = 1 i − 1 ( a [ i ] 2 − 2 ∗ a [ i ] ∗ a [ j ] + a [ j ] 2 ) = ∑ i = 2 n a [ i ] 2 ∗ ( i − 1 ) + ∑ i = 1 n − 1 a [ j ] 2 ∗ ( n − i ) − ∑ i = 2 n a [ i ] ∗ 2 ∑ j = 1 i − 1 a [ j ] \sum_{i=2}^n\sum_{j=1}^{i-1}(a[i]-a[j])^2\\ =\sum_{i=2}^n\sum_{j=1}^{i-1}(a[i]^2-2*a[i]*a[j]+a[j]^2)\\ =\sum_{i=2}^na[i]^2*(i-1)+\sum_{i=1}^{n-1}a[j]^2*(n-i)-\sum_{i=2}^na[i]*2\sum_{j=1}^{i-1}a[j]

#### code：

#include <bits/stdc++.h>
#define int long long
using namespace std;
const int maxm=2e6+5;
int cnt[maxm];
int a[maxm];
int n;
void solve(){
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i];
}
int ans=0;
//
for(int i=2;i<=n;i++){
ans+=a[i]*a[i]*(i-1);
}
//
for(int i=1;i<=n-1;i++){
ans+=a[i]*a[i]*(n-i);
}
//
int sum=a[1];
for(int i=2;i<=n;i++){
ans-=a[i]*2*sum;
sum+=a[i];
}
//
cout<<ans<<endl;
}
signed main(){
ios::sync_with_stdio(0);
solve();
return 0;
}


08-06 2154
11-07 3777
02-08 604
08-02 1008
06-10 141
01-09 422
07-22 2105