1104 Sum of Number Segments(20 分)
作者: CAO, Peng
单位: Google
时间限制: 200 ms
内存限制: 64 MB
代码长度限制: 16 KB
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 . 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
本题有明显的规律,可以使用暴力方法去解决,但是就算使用打表法去记录每一段的和值,然后再按规律计算,其算法计算次数也是不能承受的。假设有N个数字,那么就要计算以下标1开头的N个序列的和,下标2开头的N - 1个序列的和,一共需要计算 1 + 2 + 3 + ... + N - 1 + N个序列的和,根据等差序列求和公式可以得出计算次数大概有 左右,但是对于一般的OJ系统来说,一秒能够承受的运算次数大概是
~
,所以这样做很可能在给出的N较大时运算超时,所以我们需要寻求其他的解决方法。
我们可以隐约的感受到,这个计算方式一定会有数学规律可以摸索,然后直接求出每一个数字的出现次数,进而变成一个复杂度为O(N) 的运算,以给出的示例为例:
我们可以看到这是所有的需要计算求和的序列,从而我们可以得到一个表格:
下标 | 0 | 1 | 2 | 3 |
---|---|---|---|---|
次数 | 4 | 6 | 6 | 4 |
我们以相同的下标开始的序列分为一组,可以分4组,我们可以看到0.1出现在1组中,每组出现4次,0.2出现在两组中,每组出现3次,那么总结规律可以得出出现在几组中就是N - i 的值,而一组出现几次就是i + 1的值。(如果没有发现规律,可以多写几组数据总结)。
所以下标i对应的数字出现的次数就是 ( N - i ) * ( i + 1) 然后再乘上下标 i 对应的值 将 i = 0 ~ N - 1相加就是最后要求的结果了。
可以看到虽然推倒的过程略麻烦,但是最后的程序十分简洁。
AC代码:
#include <cstdio>
int main(void) {
int n;
double total = 0;
double a;
scanf("%d", &n);
for(int i = 0; i < n; ++i) {
scanf("%lf", &a);
total += (i + 1) * a * (n - i);
}
printf("%.2f\n", total);
return 0;
}
如有错误,欢迎指摘。