PAT A 1104 B 1049 (甲级 乙级)

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个序列的和,根据等差序列求和公式可以得出计算次数大概有 5*10^{8} 左右,但是对于一般的OJ系统来说,一秒能够承受的运算次数大概是10^{7} ~ 10^{8} ,所以这样做很可能在给出的N较大时运算超时,所以我们需要寻求其他的解决方法。

我们可以隐约的感受到,这个计算方式一定会有数学规律可以摸索,然后直接求出每一个数字的出现次数,进而变成一个复杂度为O(N) 的运算,以给出的示例为例:

我们可以看到这是所有的需要计算求和的序列,从而我们可以得到一个表格:

下标0123
次数4664

 

我们以相同的下标开始的序列分为一组,可以分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;
}

 


 

如有错误,欢迎指摘。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值