Time Limit: 2 sec / Memory Limit: 1024 MB
Score : 300300 points
Problem Statement
Given are NN integers A1,…,ANA1,…,AN.
Find the sum of Ai×AjAi×Aj over all pairs (i,j)(i,j) such that 1≤i<j≤N1≤i<j≤N, modulo (109+7)(109+7).
Constraints
- 2≤N≤2×1052≤N≤2×105
- 0≤Ai≤1090≤Ai≤109
- All values in input are integers.
Input
Input is given from Standard Input in the following format:
NN A1A1 …… ANAN
Output
Print ∑N−1i=1∑Nj=i+1AiAj∑i=1N−1∑j=i+1NAiAj, modulo (109+7)(109+7).
Sample Input 1 Copy
Copy
3 1 2 3
Sample Output 1 Copy
Copy
11
We have 1×2+1×3+2×3=111×2+1×3+2×3=11.
Sample Input 2 Copy
Copy
4 141421356 17320508 22360679 244949
Sample Output 2 Copy
Copy
437235829
思路;
每次选一个数,将这个数与后面所有数的相乘,相加,直接暴力TLE
而考虑优化,和后面的数相乘可以直接是o(1)的复杂度,先将所有数的和加起来,每到一个数就减去,那么就是后面的数的和了,直接拿这个数和后面的数的和相乘就行了。
注意mod
#include<bits/stdc++.h>
#define INF 0x3f3f3f3f
#define N 200003
#define pb push_back
#define x first
#define y second
#define ull unsigned long long
#define ll long long
using namespace std;
ll a[N];
const int mod = 1e9 + 7;
ll n;
ll sum;
ll res;
int main()
{
cin >> n;
for(int i = 1;i <= n;i++)
{
cin >> a[i];
sum = (sum + a[i]) % mod;
}
for(int i = 1;i <= n;i++)
{
res = (res + (a[i] * (sum - a[i] + mod) % mod) % mod) % mod;
sum = (sum - a[i] + mod) % mod;
}
cout << (res + mod) % mod<< endl;
return 0;
}