1104 Sum of Number Segments (20分)
题目描述
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.
输入格式
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.
输出格式
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时的规律。不难发现,下标为i的元素出现的次数为(i+1)*(n-i),然后再将次数乘元素值,累加可得到结果
- 但有一个问题,如果先用一个变量保存出现次数,再乘出现的次数,测试点3,和4过不去,如下代码注释所示。问题还望大佬帮我解决。
元素序号 | 1 | 2 | 3 | 4 | 5 |
---|---|---|---|---|---|
片段长度为1时出现次数 | 1 | 1 | 1 | 1 | 1 |
片段长度为2时出现次数 | 1 | 2 | 2 | 2 | 1 |
片段长度为3时出现次数 | 1 | 2 | 3 | 2 | 1 |
片段长度为4时出现次数 | 1 | 2 | 2 | 2 | 1 |
片段长度为5时出现次数 | 1 | 1 | 1 | 1 | 1 |
总次数 | 5 | 8 | 9 | 8 | 5 |
AC代码
#include<iostream>
using namespace std;
int main() {
int n;
double ans = 0.0,temp;
scanf("%d",&n);
for (int i = 0; i < n; i++) {
scanf("%lf", &temp);
//long long cnt = (i + 1)*(n - i); int可能越界,因此我分别试过long long和double
//ans += temp*cnt; 若先计算出现次数再相乘测试点3,4无法通过
ans += temp * (i + 1)*(n - i); //temp一定要写在前面,否则很可能越界
}
printf("%.2lf\n",ans);
return 0;
}