【PAT A1104】Sum of Number Segments

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.

解题思路
首先想到的自然是遍历咯,双指针,复杂度O( n^2 ),然后提交有两个样例超时;然后是数学规律解题,现分析如下,假设现在只有4个数,分别是1,2,3,4.

(1)(1,2)(1,2,3),(1,2,3,4)   ----以1开头的片段
(2)(2,3)(2,3,4)             ----以2开头的片段
(3)(3,4)                    ----以3开头的片段
(4)                         ----以4开头的片段

现在考虑1出现了多少次,1只可能出现在以1开头的片段中,不难得出其出现次数为数组的长度4;2除了可能出现在以2开头的片段中(3次),还可能出现在以1出现的片段中但不包含(1)(3次);3除了可能出现在以3开头的片段中,还可能出现在以1开头的片段中但不包含(1)(1,2)(2次),还可能出现在以2开头的片段中但不包含(2)(2次)。。现在是不是找到规律了?某个数出现在以某数开头的片段中的次数是一样的!接下来就不说了,应该很明了了。

#include <cstdio>

int main(){
	/*超时版本
	int n;
	double list[100010], sum[100010] = {0}, ans = 0;
	scanf("%d", &n);
	for(int i = 0; i < n; i++){
		scanf("%lf", &list[i]);
		sum[i + 1] = sum[i] + list[i];
	}

	int left = 0 , right = 1;
	while(left < n){
		while(right < n + 1){
			ans += sum[right] - sum[left];
			right++;
		}
		left++;
		right = left + 1;
	}
	printf("%.2lf\n", ans);
	*/
	//规律版本
	int n;
	double list[100010], sum[100010] = {0}, ans = 0;
	scanf("%d", &n);
	for(int i = 0; i < n; i++){
		scanf("%lf", &list[i]);
		ans += list[i] * (i + 1) * (n - i);
	}
	printf("%.2lf\n", ans);

	return 0;
}
发布了30 篇原创文章 · 获赞 1 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/lvmy3/article/details/104065956
今日推荐