牛客小白月赛24 J.建设道路

建设道路

https://ac.nowcoder.com/acm/contest/5158/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;
}
全部评论

相关推荐

4 收藏 评论
分享
牛客网
牛客企业服务