题意:求a中任选4个数的乘积的和
枚举4个数是N^4
如果分别枚举前2个,后2个再合起来,复杂度N^2
可以发现枚举可以用前缀和来优化,复杂度O(N)
(代码pr[i]以a[i]为第2个的两数乘积和,nt[i]是a[i]为第3个数的后两数乘积和,枚举第三数,前两数pr做前缀和)
#include <iostream>
#include <cstdio>
using namespace std;
typedef long long LL;
const LL Mod = (LL)1e9+7;
int n,a[100040];
LL pr[100040],nt[100040];
int main() {
while(~scanf("%d",&n)) {
for (int i = 1; i <= n; i++)
scanf("%d",&a[i]);
LL tp = 0;
for (int i = 1; i <= n; i++) {
pr[i] = tp*a[i]%Mod;
tp = (tp+a[i])%Mod;
}
tp = 0;
for (int i = n; i >= 1; i--) {
nt[i] = tp*a[i]%Mod;
tp = (tp+a[i])%Mod;
}
LL ans = 0;
for (int i = 2; i < n; i++) {
pr[i] = (pr[i]+pr[i-1])%Mod;
ans = (ans+pr[i]*nt[i+1]%Mod)%Mod;
}
printf("%lld\n",ans);
}
return 0;
}
链接:https://ac.nowcoder.com/acm/contest/1110/L
来源:牛客网
题目描述
Given n integers a1,a2,…,ana_1, a_2, \dots, a_na1,a2,…,an, Bobo knows how to compute the *sum of triples* S3=∑1≤i<j<k≤naiajak.S_3 = \sum_{1 \leq i < j < k \leq n} a_i a_j a_k.S3=∑1≤i<j<k≤naiajak.
It follows that S3=(∑1≤i≤nai)3−3(∑1≤i≤nai2)(∑1≤i≤nai)+2(∑1≤i≤nai3)6.S_3 = \frac{(\sum_{1 \leq i \leq n} a_i)^3 - 3 (\sum_{1 \leq i \leq n} a_i^2)(\sum_{1 \leq i \leq n} a_i) + 2(\sum_{1 \leq i \leq n} a_i^3)}{6}.S3=6(∑1≤i≤nai)3−3(∑1≤i≤nai2)(∑1≤i≤nai)+2(∑1≤i≤nai3).
Bobo would like to compute the *sum of quadrangles* (∑1≤i<j<k<l≤naiajakal) mod (109+7).\left(\sum_{1 \leq i < j < k < l \leq n} a_i a_j a_k a_l\right)\bmod (10^9+7).(∑1≤i<j<k<l≤naiajakal)mod(109+7).输入描述:
The input contains zero or more test cases and is terminated by end-of-file. For each test case, The first line contains an integer n. The second line contains n integers a1,a2,…,ana_1, a_2, \dots, a_na1,a2,…,an. * 1≤n≤1051 \leq n \leq 10^51≤n≤105 * 0≤ai≤1090 \leq a_i \leq 10^90≤ai≤109 * The number of tests cases does not exceed 10.
输出描述:
For each case, output an integer which denotes the result.
示例1
输入
复制
3 1 2 3 4 1 2 3 4 5 1 2 3 4 5
输出
复制
0 24 274