【测试点分析】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 分)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: overflow-x理解_前端系列学习笔
- 下一篇: 案例4-1.6 树种统计 (25 分)_