A1104 Sum of Number Segments (20 point(s))

简单推理

1. 原文

原题

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 105. 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:

1
2
4
0.1 0.2 0.3 0.4

Sample output:

1
5.00

2. 解析

  • 1x4x0.1

  • 2x3x0.2

  • 3x2x0.3

  • 4x1x0.4

  • (i+1)x(n-i)xnum[i]

    测试点2 double会超时

3. AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<cstdio>
double num[100010];
int main(){
int n;
scanf("%d",&n);

long long ans=0;
double a;
for (int i = 0; i < n; ++i)
{
scanf("%lf",&a);
ans+=(long long)(a*1000)*(i+1)*(n-i);
}
printf("%.2f\n", ans/1000.0);
return 0;
}

Way2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<cstdio>
long double num[100010];
int main(){
freopen("A1104.txt","r",stdin);
int n;
scanf("%d",&n);
for (int i = 0; i < n; ++i)
{
scanf("%Lf",&num[i]);
}
long double ans = 0;
for (int i = 0; i < n; ++i)
{
ans+=num[i]*(i+1)*(n-i);
}
printf("%.2Lf\n",ans);
return 0;
}
本文结束  感谢您的阅读
  • 本文作者: Wang Ting
  • 本文链接: /zh-CN/2019/09/03/A1104/
  • 发布时间: 2019-09-03 12:30
  • 更新时间: 2021-10-29 14:07
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!