【测试点分析】1104 Sum of Number Segments (20 分)
立志用更少的代碼做更高效的表達(dá)
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
解題思路
最先想到的解法一定是二重循環(huán)累加。
但一般來講, 200ms最多支持200w次左右的循環(huán)運(yùn)算, 以本題最大數(shù)據(jù)量10w次計(jì)算, 10w*10w的數(shù)據(jù)量要遠(yuǎn)遠(yuǎn)高于200w,因此常規(guī)解法行不通。
對(duì)于這種大數(shù)據(jù)量的題, 很常見的一種解法是找規(guī)律, 找到規(guī)律,推導(dǎo)出數(shù)學(xué)公式, 就可以在O(n)的數(shù)量級(jí)內(nèi)解題。
經(jīng)過推導(dǎo)我們發(fā)現(xiàn): 對(duì)于樣例輸入,有:
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
規(guī)律顯而易見, 列for循環(huán)求解即可。
提交代碼后, 發(fā)現(xiàn)樣例2無法通過
百般調(diào)試無果后, 到網(wǎng)上尋找?guī)椭?/p>
大神對(duì)此的解答是:浮點(diǎn)型精度往往是有誤差的,如1.2用浮點(diǎn)型數(shù)據(jù)保存,可能會(huì)變成:1.200003423213。
因此, 如果對(duì)浮點(diǎn)型精度進(jìn)行大數(shù)據(jù)量的運(yùn)算, 可能會(huì)導(dǎo)致誤差累積,影響最終結(jié)果。
解決辦法是: 將輸入的小數(shù)乘1000,用long long型變量存儲(chǔ), 最后除以1000輸出即可。
注意:網(wǎng)上的很多代碼并非滿分代碼,測(cè)試點(diǎn)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; }
???????——一生中總會(huì)遇到這樣的時(shí)候,你的內(nèi)心已經(jīng)兵荒馬亂天翻地覆了,可是在別人看來你只是比平時(shí)沉默了一點(diǎn),沒人會(huì)覺得奇怪。這種戰(zhàn)爭(zhēng),注定單槍匹馬。
總結(jié)
以上是生活随笔為你收集整理的【测试点分析】1104 Sum of Number Segments (20 分)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: overflow-x理解_前端系列学习笔
- 下一篇: 案例4-1.6 树种统计 (25 分)_