Artificial Intelligence Prefix Sum

insert image description here

The biggest reason for learning is to get rid of mediocrity. One day earlier, there will be more splendor in life; one day later, one day more mediocrity.

study diary

1. What is a prefix and

         The prefix sum is the sum of all array elements before (including) an item subscript of an array  .

Let b[] be the prefix sum array, and a[] be the original array. According to this sentence, the definition and recursion formula of the prefix sum can be obtained:

Definition Recursive
One-dimensional prefix sum  b[i]=\sum_{j=0}^{i}a[j] b[i]=b[i-1]+a[i]
two-dimensional prefix and b[x][y]=\sum_{i=0}^{x}\sum_{j=0}^{y}a[i][j] b[x][y]=b[x-1][y]+b[x][y-1]-b[x-1][y-1]+a[x][y]

Two, one-dimensional prefix and 

        

        According to the above definition, we can easily get sum[i] = sum[i-1] + a[i]   

In this way, the sum of the first i numbers can be obtained. According to the above expression, we can find the interval sum of the interval [i, j] with O(1)     sum[i,j]=b[j]-b[i-1]

 

It is generally used to find the sum of elements in the interval [L, R]:

ans[1]=ans[0]+q[1]

ans[2]=ans[1]+q[2]

……… ………

ans[i]=ans[i-1]+q[i]

The sum of elements between [L,R] tmp=ans[R]-ans[L-1] 

3. Two-dimensional prefixes and exercises

Original array q[ ][ ]

0

1

2

3

4

5

6

7

8

9

1

2

1

0

-1

0

2

0

0

2

1

0

0

1

2

1

1

0

0

3

2

1

1

3

1

-1

0

0

0

4

1

1

-1

0

-1

1

1

0

0

5

1

1

2

1

3

1

4

0

0

6

0

0

0

0

0

0

0

0

0

7

0

0

0

0

0

0

0

0

0

prefix and array ans[ ][ ]

0

1

2

3

4

5

6

7

8

1

1

3

4

4

3

2

2

4

5

6

7

3

4

7

9

13

15

4

5

(i-1,j)

5

6

(i,j-1)

(i , j)

6

7

求ans[ ][ ] ans[I,j]=ans[i-1,j]+ans[I,j-1]-ans[i-1][j-1]+q[i][j]:

0

1

2

3

4

5

6

7

8

1

2

(x1-1,y1-1)

(x1-1,y2)

3

(x1,y1)

4

5

(x2,y1-1)

(x2,y2)

6

7

 

Find the sum of the elements in the specified rectangle:

Upper left (x1,y1) Lower right (x2,y2)

tmp=years[x2][y2]-years[x2][y1-1]-years[x1-1][y2]+years[x1-1][y1-1] 

Guess you like

Origin blog.csdn.net/m0_63794226/article/details/126687528