2013暑假新生赛第3场 F. Help Johnny

面对复杂的球对匹配值计算任务,通过巧妙利用乘法分配律,快速解决实际问题,提升效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

F. Help Johnny

Description

Poor Johnny is so busy this term. His tutorthrew lots of hard problems to him and demanded him to accomplish thoseproblems in a month. What a wicked tutor! After cursing his tutor thousands oftimes, Johnny realized that he must start his work immediately.

The very problem Johnny should solvefirstly is about a strange machine called Warmouth. In the Warmouth there aremany pairs of balls. Each pair consists of a red ball and a blue ball and eachball is assigned a value. We can represent a pair in the form of (R, B) inwhich R is the value of the red ball and B is of the blue one. Warmouth has agenerator to calculate the match value of two pairs. The match value of (R1,B1) and (R2, B2) is R1*B2+R2*B1. Initially, Warmouth is empty. Pairs are sentinto Warmouth in order. Once a new pair comes, it will be taken into thegenerator with all the pairs already in Warmouth.

Johnny’s work is to tell his tutor the sum of all match valuesgiven the list of pairs in order. As the best friend of Johnny,would you like to help him?

Input

The first line of the input is T (no more than 10), whichstands for the number of lists Johnny received.

Each list begins with “N“(without quotes). N is thenumber of pairs of this list and is no more than 100000.

The next line gives N pairs in chronological order. The2i-th number is the value of the red ball of the i-th pair and the (2i+1)-thnumber is the value of the blue ball of the i-th pair. The numbers are positiveintegers and smaller than 100000.

Output

Please output the result in a single line for each list.

Sample Input

2

3

1 3 2 2 3 1

2

4 5 6 7

Sample Output

26

58


一个简单题,直接一个个乘的话,肯定会超时,这里利用乘法的分配率就可以顺利A掉。举个例子说就是:直接一个个算就是(R1*B2+R2*B1)+(R1*B3+R3*B1)+(R2*B3+R3*B2),用乘法的分配率就是,先算(R1*B2+R2*B1),然后把R1、B1加到R2、B2上,再乘以R3、B3。结果很快就出来了。

要注意的就是不断的累加,会使数据很大,r数组、b数组和最后的和要用64位的整型数。


#include<stdio.h>
#include<cstring>
using namespace std;

long long r[100100],b[100100];

int main()
{
	int t,n;
	int i,j;
	long long sum;
	scanf("%d",&t);
	while(t--)
	{
	    sum=0;
	    memset(r,0,100100);
	    memset(b,0,100100);
	    scanf("%d",&n);
	    for(i=1;i<=n;i++)
	    {
	        scanf("%d%d",&r[i],&b[i]);
	    }
	    for(i=1;i<n;i++)
	    {
            sum+=r[i]*b[i+1]+b[i]*r[i+1];
            r[i+1]+=r[i];
            b[i+1]+=b[i];
	    }
	    printf("%lld\n",sum);
	}
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值