Prefix Sum & Difference

First, prefixes and (basic)

Provided: a length to the number of columns n, m times ask asked [L, R] in the interval and the number of columns

1 a[0]=0;
2 for(int i=1;i<=n;i++)a[i]+=a[i-1];

Therefore, the foregoing is the sum of i and the prefix number, the seek is the section and a [R] -a [L-1]

Second, the difference (basic)

Provided: a given length n, the number of columns of [L, R] range plus or minus a certain value, finally asked [L, R] of the interval and the number of columns

 1 #include<bits/stdc++.h>
 2 #define mem(a) memset(a,0,sizeof(a))
 3 #define ll long long
 4 #define inf 0x3f3f3f3f
 5 const int N=1e6+5;
 6 using namespace std;
 7 int main(){
 8    int n,m,a[100],b[100];
 9    cin>>n>>m;
10    for(int i=1;i<=n;i++){
11     cin>>a[i];
12    }
13    for(int i=1;i<=m;i++){
14       int l,r,t,p;
15       cin>>t>>l>>r>>p;
16       if(t==1){
17         b[l]+=p;
18         b[r+1]-=p;//只考虑[l,r]范围
19       }
20    }
21    int add=0;
22    for(int i=1;i<=n;i++){
23         add+=b[i];
24         a[i]+=a[i-1]+add;
25    }
26    int L,R;
27    cin>>L>>R;
28    cout<<a[R]-a[L-1]<<endl;
29    return 0;
30 }

Third, the two-dimensional prefix and

Premise: Given a matrix of size n * m a, q times with a query, query given every x1, y1, x2, y2 four numbers, seeking to (x1, y1) and the coordinates of the upper left corner (x2, y2 ) all the elements and the bottom right coordinates for the sub-matrix. // inclusive

ans=a[x2][y2]-a[x1-1][y2]-a[x2][y1-1]+a[x1-1][y1-1]

a[i][j]+=a[i][j-1]+a[i-1][j]-a[i-1][j-1]

 1 #include<bits/stdc++.h>
 2 #define mem(a) memset(a,0,sizeof(a))
 3 #define ll long long
 4 #define inf 0x3f3f3f3f
 5 const int N=1e6+5;
 6 using namespace std;
 7 int main(){
 8    int n,m,a[N][N],q;
 9    cin>>n>>m>>q;
10    for(int i=1;i<=n;i++){
11      for(int j=1;j<=m;j++)
12         cin>>a[i][j];
13    }
14    for(int i=1;i<=n;i++){
15      for(int j=1;j<=m;j++)
16         a[i][j]+=a[i][j-1]+a[i-1][j]-a[i-1][j-1];
17    }
18    for(int i=1;i<=q;i++){
19     int x1,y1,x2,y2;
20     cin>>x1>>y1>>x2>>y2;
21     cout<<a[x2][y2]-a[x1-1][y2]-a[x2][y1-1]+<<endl;
22    }
23    return 0;
24 }

 

Guess you like

Origin www.cnblogs.com/XXrll/p/11105333.html