Niuke.com DP34 [Template] Prefix sum (high-quality solution)

Code:

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextInt()) { // 注意 while 处理多个 case
            int n=in.nextInt();
            int q=in.nextInt();

            int[]arr=new int[n+1];

            for(int i=1;i<=n;i++){
                arr[i]=in.nextInt();
            }

            //计算数组 arr 对应的前缀和数组
            long[]dp=new long[n+1];
            for(int i=1;i<=n;i++){
                dp[i]=dp[i-1]+arr[i];
            }

            while(q!=0){
                int l=in.nextInt();
                int r=in.nextInt();

                System.out.println(dp[r]-dp[l-1]);
                q--;
            }

        }
    }
}

answer:

        This question is the simplest question about prefix sum type. It is used to understand the prefix sum method.

        There is a very simple brute force solution to this problem. The time complexity is O(nq). You can traverse directly according to the input range to get the result. You can traverse as many times as you want. However, using a brute force solution to this problem will definitely time out.

        For frequently calculating the sum of data in an interval, we can usually use the method of prefix sum to solve this problem. The idea of ​​​​prefix sum is a bit Like dynamic programming, we can create an array dp to store the sum of data from the starting point to the position. For example, in this question, we can create an array dp of size n+1, dp[i] means subscript from 1 Sum of data to index i

        Taking the data 1, 2, 4, 5, 7, 6 as an example, according to the meaning of the question, we know that in the question, the subscript of the array starts from 1, and the subscript of our dp array should also start from 1 Starting from In order to eliminate boundary problems, we will mention later), in the dp array, assume that we want to calculate the value of dp[ i ], that is To get the data sum of subscript 1~i, we can first get the value of 1~i-1, which is dp[i-1], plus arr[i], so we getThe equation to fill the dp array dp[ i ] = dp[ i-1 ] + arr[ i ] , because when i =0, dp[ 0 ] = dp[ -1 ] + arr[0], out of bounds, so the dp array starts from subscript 1

        After filling the dp array, we need to use the dp array to solve the problem. Assume l =3, r = 5. To obtain the data sum of subscripts 3~5, we can use the data sum of 1~5 and dp[5] minus The data of 1~2 and dp[2], that is, dp[r] - dp[l-1], so the result we want to obtain is result = dp[r] - dp[l-1]

Guess you like

Origin blog.csdn.net/q322359/article/details/135031407
Recommended