A 1104 Sum of Number Segments
Problem Description
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
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
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
解题思路:
观察样例,一共4个元素,每种元素各自有4(0.1开头)、3(0.2开头)、2(0.3开头)、1(0.4开头)种情况累加。对于每个元素k[i]的累加,其结果刚好是前一个元素k[i-1]的累加结果减去(n-i+2)个前一个元素k[i-1]的值 。可以通过递推累加的方式完成所有元素的计算,且不会超时。如果不用long double去用double,第三个测试点无法通过
AC代码
#include<bits/stdc++.h>
using namespace std;
const int maxn = 100005;
long double dp[maxn],db[maxn],ans=0.0,temp=0.0;
int n;
int main(){
scanf("%d",&n);
dp[0]=0.0;
for(int i=1;i<=n;i++){
scanf("%llf",&dp[i]);
}
for(int i=1;i<=n;i++){
db[i]=dp[i];
dp[i]+=dp[i-1];
}
for(int i=1;i<=n;i++){
temp+=dp[i];
}
ans+=temp;
for(int i=2;i<=n;i++){
temp-=(n-i+2)*db[i-1];
ans+=temp;
}
printf("%.2llf",ans);
return 0;
}