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] i=2nj=1i1(a[i]a[j])2=i=2nj=1i1(a[i]22a[i]a[j]+a[j]2)=i=2na[i]2(i1)+i=1n1a[j]2(ni)i=2na[i]2j=1i1a[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;
}

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 游动-白 设计师:白松林 返回首页