牛客小白月赛24 J.建设道路(数学)

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;
}

猜你喜欢

转载自blog.csdn.net/weixin_43731933/article/details/105607775