黑龙江大学程序设计竞赛(重现赛)B - Help Me(思维)

题目链接:https://ac.nowcoder.com/acm/contest/877/B

思路 : 比如4个数a_{1}a_{2}a_{3}a_{4},答案应该是它们(a_{1}-a_{2})^{2},(a_{1}-a_{4})^{2},(a_{2}-a_{4})^{2},(a_{3}-a_{4})^{2},(a_{1}-a_{3})^{2},(a_{2}-a_{3})^{2}的和,我们拆开发现,(n-1)*(a_{1}^{2}+a_{2}^{2}+a_{3}^{2}+a_{4}^{2})-2a_{1}a_{2}-(a_{1}+a_{2})*a_{3}-(a_{1}+a_{2}+a_{3})*a_{4},这样我们维护个前缀和就好了。

#include
using namespace std;
typedef long long ll;
const int MAXN = 5e4 + 5;
int n;
int a[MAXN];
int main()
{
    int T;
    scanf("%d", &T);
    while(T--)
    {
        scanf("%d", &n);
        ll ans = 0;
        for(int i = 1; i <= n; i++)
        {
            scanf("%d", &a[i]);
            ans += 1LL * (n - 1) * a[i] * a[i];
            ans -= 2LL * a[i - 1] * a[i];
            a[i] += a[i - 1];
        }
        printf("%lld\n", ans);
    }
    return 0;
}

 

你可能感兴趣的:(【思维】)