当前位置: 代码迷 >> 综合 >> [PAT B1049/A1104]Sum of Number Segments
  详细解决方案

[PAT B1049/A1104]Sum of Number Segments

热度:73   发布时间:2023-12-15 06:16:24.0

[PAT B1049/A1104]Sum of Number Segments

本题是PAT乙级1049题和甲级1104题,所以先放英文原题,如果要做乙级题的小伙伴可以直接跳过看后面的中文原题

题目描述

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 10?5??. 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.

输入样例

4
0.1 0.2 0.3 0.4

输出样例

5.00

-----------------------中文原题------------------------------

题目描述

1049 数列的片段和 (20 分)给定一个正数数列,我们可以从中截取任意的连续的几个数,称为片段。例如,给定数列 { 0.1, 0.2, 0.3, 0.4 },我们有 (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) 这 10 个片段。
给定正整数数列,求出全部片段包含的所有的数之和。如本例中 10 个片段总和是 0.1 + 0.3 + 0.6 + 1.0 + 0.2 + 0.5 + 0.9 + 0.3 + 0.7 + 0.4 = 5.0。

输入格式

输入第一行给出一个不超过 10?5?? 的正整数 N,表示数列中数的个数,第二行给出 N 个不超过 1.0 的正数,是数列中的数,其间以空格分隔。

输出格式

在一行中输出该序列所有片段包含的数之和,精确到小数点后 2 位。

解析

  1. 题目可以说是很简单了,就是找规律,一个数在片段中出现了几次可以使用i*(n-i+1)来计算,这里我有些画蛇添足了,使用了一个新数组存储乘的次数,没必要,直接在输入的过程中就可以计算出来了。
  2. 这题最需要小心的地方就是溢出问题,因为i*(n-i+1)都是整数,相乘是很有可能发生溢出的,所以要使用强制类型转换,否则过不了。
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
long long num[100010] = {
     0 };
double v[100010] = {
     0.0 };
using namespace std;
int main() 
{
    int n;scanf("%d", &n);for (int i = 1; i <= n; i++) {
    scanf("%lf", &v[i]);}for (int i = 1; i <= n; i++) {
    num[i] = i*(long long)(n - i + 1);}double ans = 0.0;for (int i = 1; i <= n; i++)ans += num[i] * v[i];printf("%.2f", ans);return 0;
}

水平有限,如果代码有任何问题或者有不明白的地方,欢迎在留言区评论;也欢迎各位提出宝贵的意见!

  相关解决方案