思路解析:
如果用通常的办法总是会显示TLE(Time Limit Exceeded),为了降低复杂度,可以如下计算:
关键是把每一个(a[i] - a[x])^2的和分解开来去算:
每一项a[i]^2的和做一项,a[x]的和做一项,2*a[i]a[x]做一项;
三项分开计算后相加就能避免TLE
代码如下:
#include <iostream>
#define LL long long
using namespace std;
int main()
{
LL n,sum = 0,sum1 = 0;
cin >> n;
LL a[n];
for(int i = 0 ; i < n ; i ++){
cin >> a[i];
sum += a[i] * a[i];
sum1 += a[i];
}
for(int i = 0 ; i < n ; i ++){
LL t = 0;
t = sum + n * a[i] * a[i] - 2 * a[i] * sum1;
if(i != n-1) cout << t << " ";
else cout << t;
}
return 0;
}