And prefix, prefix and two-dimensional differential

Prefix and

If a string of length n is given number of rows a1, a2, a3 ... an, and then give the m inquiry, each query given L, R of two numbers, the number of columns in the interval required to give [L, R] and

Conventional method, time complexity is O (n * m)

int a[100005];
for(int i=1;i<=n;i++){
    scanf("%d",&a[i]);
}
int sum=0;
while(m--){
    for(int i=L;i<=R;i++){
        sum+=a[i];
    }
}

And the sum is in front of the prefix number i, for each interrogation, only the output of a [R] -a [L- 1] to
a prefix and the method, time complexity of O (m + n)
prefix and Determination

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

The difference

If a string of length n is given number of rows a1, a2, a3 ... an, and then give different views of L m and R [L, R] Operation
Operation a: elements within the [L, R] are plus P
operation II: the elements within the [L, R] P subtracted
elements within the last request [L, R] and

Common methods of time complexity O (m * n)

Using differential

#include <bits/stdc++.h>
using namespace std;
const int manx=1e5+5;
int a[maxn],b[maxn];
int main(){
    int n,m;
    cin>>n>>m;
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
    }
    for(int i=1;i<=m;i++){
        int l,r,t,p;//t为操作类型,p为加减的大小
        cin>>t>>l>>r>>p;
        if(t==1){//t==1表示加
            b[l]+=p;b[r+1]-=p;//因为操作一我只需对[L,R]区间里的数加p,[R+1,n]这个区间里的数没必要加p,所以需要减掉p。
        }else{//t==0表示减
            b[l]-=p;b[r+1]+=p;
        }
    }
    int add=0;
    for(int i=1;i<=n;i++){
        add+=b[i];
        a[i]+=a[i-1]+add;
    }
    cin>>l>>r;
    printf("%d\n",a[r]-a[l-1]);
    return 0;
}

And two-dimensional prefix

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) of All elements of the lower right corner coordinates and sub-matrices. Note that still contain elements of left and right corners.

Seeking dimensional prefix and
n rows and m columns

memset(a,0,sizeof(a));
for(int i=1;i<=n;i++){
    for(int j=1;j<=m;j++){
        if(j==1)a[i][j]+=a[i-1][j];
        else a[i][j]+=a[i][j-1]+a[i-1][j]-a[i-1][j-1];//因为a[i-1][j-1]的值被加了两次
    }
}

2. 3. 1
2. 1 2
2. 1. 1
prefix and
. 1. 3. 6
. 3. 6. 11
. 5 15. 9

Guess you like

Origin www.cnblogs.com/Emcikem/p/11351353.html