Cometoj出過這題。。
考慮單個點的貢獻
(a[i] - a[x]) * (a[i] - a[x]) = a[i] * a[i] - 2 * a[i]* a[x] + a[x] * a[x]
所以裏面一共就有(n - 1)個a[i]的平方以及除了a[i]外其他所有數的平方,中間這部分減法就是
2 * (sum - a[i]) * a[i], sum即是所有數字的和。
最後別忘了除2,因爲兩兩之間會算兩次。
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int N = 1e6 + 10;
const int mod = 1e9 + 7;
const int INF = 0x3f3f3f3f;
const int LINF = 0x3f3f3f3f3f3f3f3f;
ll a[N];
ll fpow(ll a, ll b) { ll res = 1; for (; b > 0; b >>= 1) { if (b & 1) res = res * a % mod; a = a * a % mod; } return res; }
int main()
{
#ifdef LOCAL
freopen("E:/input.txt", "r", stdin);
#endif
int n;
cin >> n;
ll sum = 0, tot = 0;
for (int i = 1; i <= n; i++)
{
cin >> a[i];
sum = (sum + a[i]) % mod;
tot = (tot + a[i] * a[i] % mod) % mod;
}
ll ans = 0;
for (int i = 1; i <= n; i++)
{
ans = (ans + (n - 1) * a[i] % mod * a[i] % mod + (tot - a[i] * a[i] % mod + mod) % mod - 2 * a[i] * (sum - a[i]) % mod + mod) % mod;
}
cout << ans * fpow(2LL, mod - 2) % mod << endl;
return 0;
}