PTA甲级 1104 Sum of Number Segments (20分)


强烈推荐,刷PTA的朋友都认识一下柳神–PTA解法大佬

本文由参考于柳神博客写成

柳神的CSDN博客,这个可以搜索文章

柳神的个人博客,这个没有广告,但是不能搜索

这题还有一个大佬的博客—就是他发现了数据的错误–

地址如下

题目原文

1104Sum of Number Segments(20分)

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 Specification:

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 105. The next line contains N positive numbers in the sequence, each no more than 1.0, separated by a space.

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

Thanks to Ruihan Zheng for correcting the test data.

思路如下:

这题可以很明显的发现规律.

如果当前是第i个数,那么其总的出现次数等于i*(n+1-i)

PS:要注意,这题不能用double直接算,因为在计算机中,double会损失精度,会让计算结果出现偏差

柳神的代码如下:

#include <iostream>
using namespace std;
int main() {
    int n;
    cin >> n;
    long long sum = 0;
    double temp;
    for (int i = 1; i <= n; i++) { 
        cin >> temp;
        //这里这样写的原因是应为,double类型会损失精度,在这题里面,会报错,所以,我们要用longlong 然后在除
        sum += (long long)(temp * 1000) * i * (n - i + 1);
    }
    printf("%.2f", sum / 1000.0);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Huangpengyu123/article/details/107117245
今日推荐