Fragments of PAT Class B 1049 data (problem-solving ideas + AC codes)

topic:

Given a sequence of positive numbers, we can intercept any consecutive numbers from it, called fragments. For example, given the sequence { 0.1, 0.2, 0.3, 0.4 }, we have (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) These 10 fragments.

Given a sequence of positive integers, find the sum of all numbers contained in all segments. For example, the sum of 10 segments in this example is 0.1 + 0.3 + 0.6 + 1.0 + 0.2 + 0.5 + 0.9 + 0.3 + 0.7 + 0.4 = 5.0.

Input format:

Input the first line to give a positive integer N not exceeding 105 , indicating the number of numbers in the sequence, and the second line to give N positive numbers not exceeding 1.0, which are the numbers in the sequence, separated by a space.

Output format:

Print on one line the sum of the numbers contained in all fragments of this sequence, accurate to 2 decimal places.

Input sample:

4
0.1 0.2 0.3 0.4

Sample output:

5.00

Code length limit 16 KB
Java (javac) time limit 500 ms
memory limit 128 MB
other compiler time limit 200 ms
memory limit 64 MB

 

problem solving ideas

For this kind of question, we focus on finding the law, 5.00 = 0.1 * 4 * 1 + 0.2 * 3 * 2 + 0.3 * 2 * 3 + 0.4 * 1 * 4, so we only need to use a for loop to loop n times. But since decimals lose precision when stored in a computer, the best way is to multiply the decimal by a number of 1000 or greater, and then divide by that number. For example, 0.1+0.2 means (0.1*1000+0.2*1000)/1000 and the result will not change.

 

AC code

#include <stdio.h>

int main()
{
    
    
    int n = 0;
    scanf("%d", &n);
    long long sum = 0;
    for (int i = 1; i <= n; i++)
    {
    
    
        double tmp;
        scanf("%lf", &tmp);
        sum += (long long)(tmp * 1000 * i * (n - i + 1));
    }
    printf("%.2lf", sum / 1000.0);
    return 0;
}

Guess you like

Origin blog.csdn.net/m0_70103775/article/details/131219965