一、题目描述
Input Specification:
Output Specification:
For each test case, print in one line the sum of all the numbers in all the segments, accurate up to 2 decimal places.
Sample Input:
4
0.1 0.2 0.3 0.4
Sample Output:
5.00
二、解题思路
一道十分巧妙的数学题,如果按正常顺序进行循环,那我们要建立一个三重循环计算总和,但是如果我们换一种思路来计算就非常简单了,我们可以把计算总和的过程写成如下形式:
每一个数对结果的贡献实际取决于前面有多少个数和后面有多少个数,比如样例中的0.2,前面有一个元素,后面有2个元素,(2+1)*(1+1) = 6,所以6×0.2加入结果中。故代码十分简单,如下。
三、AC代码
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
int N;
scanf("%d", &N);
double sum = 0.0, tmp;
for(int i=0; i<N; i++)
{
scanf("%lf", &tmp);
sum += tmp * (N-i) * (i+1);
}
printf("%.2f", sum);
return 0;
}