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 1. 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
题意:
给出一组数字,求这组数字各个连续子段的和。
思路:
由数组中的一个数字组成的片段假设是temp:1,2,3,4,5,temp(i),7,8,9。则该片段的起始位置有 i 种不同的可能,结束位置有(n - i + 1)种不同的可能。所以,temp出现的总的次数就是 i * (n - i + 1)。遍历数组然后将不同的temp出现的次数相加即可。
Code:
1 #include <bits/stdc++.h> 2 3 using namespace std; 4 5 int main() { 6 int n; 7 cin >> n; 8 double ans = 0.0, temp; 9 10 for (int i = 1; i <= n; ++i) { 11 cin >> temp; 12 ans = ans + temp * i * (n - i + 1); 13 } 14 15 cout << fixed << setprecision(2) << ans << endl; 16 return 0; 17 }
刚开始想着用遍历的方法来做,但是这样做的话最后两组数据不能够通过。后来想到用数学的方法,但是自己想到的方法太弱,还是没能过。后来就看别人的代码了,现在觉得自己还是那么菜。
2020-07-12 21:41:57
刚才又提交了一下这道题,发现上次全部通过的测试点,这次有一组数据没有通过。后来发现原来是被一位大佬找到了错误修改了测试点,大佬的水平我只能够仰望。https://blog.zhengrh.com/post/about-double/
AC代码:
1 #include <bits/stdc++.h> 2 3 using namespace std; 4 5 int main() { 6 int n; 7 cin >> n; 8 long long ans = 0; 9 double temp; 10 11 for (int i = 1; i <= n; ++i) { 12 cin >> temp; 13 ans += (long long)(temp * 1000) * i * (n - i + 1); 14 } 15 16 cout << fixed << setprecision(2) << (double)(ans / 1000.0) << endl; 17 return 0; 18 }
00000