1104. Sum of Number Segments (20)

来源:互联网 发布:大数据对日常生活影响 编辑:程序博客网 时间:2024/04/30 09:08

1104. Sum of Number Segments (20)

时间限制
200 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CAO, Peng

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) (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:
40.1 0.2 0.3 0.4 
Sample Output:
5.00

提交代码

http://www.patest.cn/contests/pat-a-practise/1104

是一道数学题,不过容易超时,就是在输入的时候需要直接就进行处理 ,双重for不行

计算0.1时,0.1 算了n次,0.2算了n-1次, 0.3算了n-2次 。。。

计算0.2时,0.2 算了n-1次,0.3算了n-2次 。。。


所以 当有n个数的时候. 计算第i个数的时候

第0个数 算了 n 次

第1个数 算了 (n-1) * 2

第2个数 算了 (n-2) * 3

所以规律是 第i个数计算次数 (n-i)*(i+1) (i=0,1,2,3 .....)


15分代码:

#include <cstdio>#include <cstdlib>#include <vector>#include <algorithm>using namespace std ;#define N 100001int main(){  //freopen("in.txt" , "r" , stdin) ;  int n , i , j ;  double a[N] ;  scanf("%d" , &n) ;  for(i = 0 ; i < n ; i++)  {    scanf("%lf" , &a[i]) ;   }  double sum = 0 ;  for(i = 0 ; i < n ; i++)  {      double sumTmp = 0 ;    for(j = n - i  ; j >= 1 ; j --)    {      sumTmp += a[n - j] * j ;    }    sum += sumTmp ;  }  printf("%.2lf\n" , sum) ;  return 0 ;  }


ac代码:

#include <cstdio>#include <cstdlib>#include <vector>#include <algorithm>using namespace std ;#define N 100001int main(){  //freopen("in.txt" , "r" , stdin) ;  int n , i , j ;  double a[N] ;  scanf("%d" , &n) ;  double sum  = 0 ;  for(i = 0 ; i < n ; i++)  {    scanf("%lf" , &a[i]) ;     double sumTmp = a[i] * (n - i) *(i + 1) ;    sum += sumTmp ;  }  printf("%.2lf\n" , sum) ;  return 0 ;  }



0 0