4644. 求和
https://www.acwing.com/problem/content/description/4647/
第十三届蓝桥杯省赛C++A/C组 , 第十三届蓝桥杯省赛JAVAA组
算法标签:推公式;前缀和
思路
-
推公式做法:
( a 1 + a 2 + a 3 + . . . + a n ) 2 = a 1 2 + a 2 2 + a 3 2 + . . . + a n 2 + 2 × a 1 × a 2 + 2 × a 1 × a 3 + . . . + 2 × a 1 × a n + 2 × a 2 × a 3 + . . . + 2 × a n − 2 × a n − 1 + 2 × a n − 2 × a n + 2 × a n − 1 × a n = a 1 2 + a 2 2 + a 3 2 + . . . + a n 2 + 2 × S (a_1+a_2+a_3+...+a_n)^2 = a_1^2 + a_2^2 + a_3^2 + ... + a_n^2 + 2\times a_1 \times a_2 + 2\times a_1 \times a_3 + ... + 2\times a_1 \times a_n + 2 \times a_2 \times a_3 + ... + 2 \times a_{n-2} \times a_{n-1} + 2 \times a_{n-2} \times a_n + 2\times a_{n-1} \times a_n = a_1^2 + a_2^2 + a_3^2 + ... + a_n^2 + 2\times S (a1+a2+a3+...+an)2=a12+a22+a32+...+an2+2×a1×a2+2×a1×a3+...+2×a1×an+2×a2×a3+...+2×an−2×an−1+2×an−2×an+2×an−1×an=a12+a22+a32+...+an2+2×S -
前缀和做法
S = ∑ i = 1 n − 1 a i × ( s n − s i ) S = \sum_{i=1}^{n-1} a_i\times(s_n - s_{i}) S=i=1∑n−1ai×(sn−si)
C++代码
思路1
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int N = 200010;
ll res, sum;
int n;
int main()
{
cin >> n;
for (int i = 0, t; i < n; i ++) cin >> t, res += t, sum += t * t;
cout << (res * res - sum) / 2 << endl;
return 0;
}
思路2
// (a + b + c)^2 = a^2 + b^2 + c^2 + 2ab + 2ac + 2bc
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int N = 200010;
ll res;
int sum[N], a[N];
int n;
int main()
{
cin >> n;
for (int i = 1; i <= n; i ++) cin >> a[i], sum[i] = a[i] + sum[i-1];
for (int i = 1; i <= n-1; i ++) res += (ll)a[i] * (sum[n] - sum[i]);
cout << res << endl;
return 0;
}