AtCoder Beginner Contest 177 --- C - Sum of product of pairs(类似前缀和,双指针的优化)

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;
}


 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值