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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章