PAT甲级1104 Sum of Number Segments (20分)|C++实现

一、题目描述

原题链接
在这里插入图片描述

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;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值