【剑指紫金港】1104 Sum of Number Segments

A 1104 Sum of Number Segments

题目链接

Problem Description

Given a sequence of positive numbers, a segment is defined to be a consecutive subsequence. For example, given the sequence { 0.1, 0.2, 0.3, 0.4 }, we have 10 segments: (0.1) (0.1, 0.2) (0.1, 0.2, 0.3) (0.1, 0.2, 0.3, 0.4) (0.2) (0.2, 0.3) (0.2, 0.3, 0.4) (0.3) (0.3, 0.4) and (0.4).

Now given a sequence, you are supposed to find the sum of all the numbers in all the segments. For the previous example, the sum of all the 10 segments is 0.1 + 0.3 + 0.6 + 1.0 + 0.2 + 0.5 + 0.9 + 0.3 + 0.7 + 0.4 = 5.0.

Input

Each input file contains one test case. For each case, the first line gives a positive integer N, the size of the sequence which is no more than 10​5​​ . The next line contains N positive numbers in the sequence, each no more than 1.0, separated by a space.

Output

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

解题思路

观察样例,一共4个元素,每种元素各自有4(0.1开头)、3(0.2开头)、2(0.3开头)、1(0.4开头)种情况累加。对于每个元素k[i]的累加,其结果刚好是前一个元素k[i-1]的累加结果减去(n-i+2)个前一个元素k[i-1]的值 。可以通过递推累加的方式完成所有元素的计算,且不会超时。如果不用long double去用double,第三个测试点无法通过

AC代码

#include<bits/stdc++.h>
using namespace std;
const int maxn = 100005;

long double dp[maxn],db[maxn],ans=0.0,temp=0.0;
int n;

int main(){
    scanf("%d",&n);
    dp[0]=0.0;
    for(int i=1;i<=n;i++){
        scanf("%llf",&dp[i]);
    }
    for(int i=1;i<=n;i++){
        db[i]=dp[i];
        dp[i]+=dp[i-1];
    }
    for(int i=1;i<=n;i++){
        temp+=dp[i];
    }
    ans+=temp;
    for(int i=2;i<=n;i++){
        temp-=(n-i+2)*db[i-1];
        ans+=temp;
    }
    printf("%.2llf",ans);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

征服所有不服

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值