Prefixes and detailed explanations

Question: There is a sequence of length n, m times of query, sum the interval [l, r]

enter:

The first line contains two positive integers n and m (the meaning of n is as above, m represents the number of queries)

The second line inputs a positive integer sequence of length n (a1,a2,a3,…,an-1,an)

The number of incoming numbers l , r , the number of incoming numbers per m row, the sum of the outgoing numbers [l, r] intervals
(1≤n≤103 ,0≤ai ≤1012,1≤m≤106 , l≤r≤n)
Output:
Each row outbound area [l, r] Ward interval
Example:
SampleInput
10 5
1 6 7 2 21 4 8 3 16 7
1 3
7 9
1 5
4 6 37< /span> 41 27 27 14 SampleOutput
1 6





This question is a typical prefix sum problem. If brute force is used to solve it, the time complexity is 1e3*1e6=1e9, which is obviously TLE. Therefore, we must consider algorithm optimization, and the time complexity of prefix sum O(1) is just right. can solve this problem.

What is the prefix sum? Let’s first look at a sequence:
Please add image description
If we want to find the value from position three to position six, that isPlease add image description

We can open a sum array and process it in this way, so that the value of sum[i] at each position is equal to itself and the sum of all previous items. In this case, the resulting sum array looks like this< a i=1> If we want to get the interval sum from l~r, we only need to output sum[r]-sum[l-1], that is, the sum of the first r terms minus the sum of the first l-1 terms We call the sum array a prefix sum array, which is a one-dimensional prefix sum
Please add image description

Please add image description

ans=sum[r]-sum[l-1];

In a two-dimensional array, if we want to find the sum of the intervals from point (L1, R1) to point (L2, R2)Please add image description
, we need to use the method from the upper left corner to (L2 , R2) minus two green parts. In the process of subtracting the green part, the black shaded part is subtracted twice, so a sum of the black shaded part must be added.

ans=sum[L2][R2]-sum[L1-1][R2]-sum[L2][R1-1]+sum[L1-1][R1-1];

Template question code Accode:

#include<bits/stdc++.h>
using namespace std ;
typedef long long ll ;
ll a[1005];
ll sum[1005];
int main (){
    
     

   int n,m; cin >> n >> m ;
   for(int i = 1 ;i<=n;i++){
    
     
     cin >> a[i];
     sum[i] = a[i] + sum[i-1];
   }
   while(m--){
    
     
     int x,y;
     cin >> x >> y ;
     cout<<sum[y] - sum[x-1]<<endl;
   }
  return 0 ;
}

Guess you like

Origin blog.csdn.net/Stephen_Curry___/article/details/126946935