日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

【测试点分析】1104 Sum of Number Segments (20 分)

發布時間:2024/2/28 44 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【测试点分析】1104 Sum 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 10^5. 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


解題思路

最先想到的解法一定是二重循環累加。

一般來講, 200ms最多支持200w次左右的循環運算, 以本題最大數據量10w次計算, 10w*10w的數據量要遠遠高于200w,因此常規解法行不通。

對于這種大數據量的題, 很常見的一種解法是找規律, 找到規律,推導出數學公式, 就可以在O(n)的數量級內解題。

經過推導我們發現: 對于樣例輸入,有:
sum=0.1?1?4+0.2?2?3+0.3?3?2+0.4?4?1sum = 0.1*1*4 + 0.2*2*3 + 0.3*3*2 + 0.4*4*1sum=0.1?1?4+0.2?2?3+0.3?3?2+0.4?4?1

規律顯而易見, 列for循環求解即可。

提交代碼后, 發現樣例2無法通過

百般調試無果后, 到網上尋找幫助。

大神對此的解答是:浮點型精度往往是有誤差的,如1.2用浮點型數據保存,可能會變成:1.200003423213。
因此, 如果對浮點型精度進行大數據量的運算, 可能會導致誤差累積,影響最終結果。

解決辦法是: 將輸入的小數乘1000,用long long型變量存儲, 最后除以1000輸出即可。

注意:網上的很多代碼并非滿分代碼,測試點2無法通過!一定要注意甄別!


#include<bits/stdc++.h> using namespace std; using gg = long long; int main() {gg n; scanf("%lld", &n);gg sum = 0;double x;for(gg i = 1; i <= n; i++) {scanf("%lf", &x);gg x1 = (gg)(x*10000+5)/10;sum += x1*(i*(n-i+1));}printf("%.2lf", (double)(sum/1000.0)); return 0; }

???????——一生中總會遇到這樣的時候,你的內心已經兵荒馬亂天翻地覆了,可是在別人看來你只是比平時沉默了一點,沒人會覺得奇怪。這種戰爭,注定單槍匹馬。

總結

以上是生活随笔為你收集整理的【测试点分析】1104 Sum of Number Segments (20 分)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。