对于二维数组求前缀和,我们先预处理第一行跟第一列的前缀和
第一行跟第一列的前缀和可以看作一维数组的前缀和
前缀和数组的0,0等于原数组的0,0,第一行为原数组第一行的前缀和,第一列为第一列的前缀和
预处理:
//原数组
int arr[110][110]={
{},
{0,1,2,3,4,5,6,7,8,9,0},
{0,6,7,8,9,0,1,2,3,4,5},
{0,1,2,3,4,5,6,7,8,9,0},
{0,1,2,3,4,5,6,7,8,9,0},
{0,1,2,3,4,5,6,7,8,9,0},
{0,1,2,3,4,5,6,7,8,9,0},
{0,1,2,3,4,5,6,7,8,9,0},
{0,1,2,3,4,5,6,7,8,9,0},
{0,1,2,3,4,5,6,7,8,9,0},
{0,1,2,3,4,5,6,7,8,9,0},
};
int sum[110][110]={0};//前缀和数组
//预处理
sum[1][1]=arr[1][1];
for(int i=2;i<=10;i++) {
sum[1][i]=arr[1][i]+sum[1][i-1];
sum[i][1]=arr[i][1]+sum[i-1][1];
}
遍历剩下的部分求前缀和:
如图不难看出 ( x , y ) (x,y) (x,y)前缀和等于 ( x − 1 , y ) (x-1,y) (x−1,y)的前缀和加上 ( x , y − 1 ) (x,y-1) (x,y−1)的前缀和再减去一次重叠部分 ( x − 1 , y − 1 ) (x-1,y-1) (x−1,y−1)的前缀和,最后再加上数组本身的 ( x , y ) (x,y) (x,y)
代码:
//原数组
int arr[110][110]={
{},
{0,1,2,3,4,5,6,7,8,9,0},
{0,6,7,8,9,0,1,2,3,4,5},
{0,1,2,3,4,5,6,7,8,9,0},
{0,1,2,3,4,5,6,7,8,9,0},
{0,1,2,3,4,5,6,7,8,9,0},
{0,1,2,3,4,5,6,7,8,9,0},
{0,1,2,3,4,5,6,7,8,9,0},
{0,1,2,3,4,5,6,7,8,9,0},
{0,1,2,3,4,5,6,7,8,9,0},
{0,1,2,3,4,5,6,7,8,9,0},
};
int sum[110][110]={0};//前缀和数组
//预处理
sum[1][1]=arr[1][1];
for(int i=2;i<=10;i++) {
sum[1][i]=arr[1][i]+sum[1][i-1];
sum[i][1]=arr[i][1]+sum[i-1][1];
}
//剩下的部分求和代码
for(int i=2;i<=10;i++){
for(int o=2;o<=10;o++){
sum[i][o]=sum[i-1][o]+sum[i][o-1]-sum[i-1][o-1]+arr[i][o];
}
}
这样就求出来二维数组的前缀和
区间和:
求二维数组 ( x 1 , y 1 ) − > ( x 2 , y 2 ) (x1,y1)->(x2,y2) (x1,y1)−>(x2,y2)的和 ( x 1 < = x 2 ) ( y 1 < = y 2 ) (x1<=x2) (y1<=y2) (x1<=x2)(y1<=y2)
求出前缀和之后,我们可以以 O ( 1 ) O(1) O(1)的速度求出来
求 ( x 1 , y 1 ) − > ( x 2 , y 2 ) (x1,y1)->(x2,y2) (x1,y1)−>(x2,y2)的值应该等于 ( x 2 , y 2 ) (x2,y2) (x2,y2)的前缀和减去( x 1 − 1 , y 2 ) , ( x 2 , y 1 − 1 ) x1-1,y2),(x2,y1-1) x1−1,y2),(x2,y1−1)的前缀和再加上重叠部分 ( x 1 − 1 , y 1 − 1 ) (x1-1,y1-1) (x1−1,y1−1)的和就是 ( x 1 , y 1 ) − > ( x 2 , y 2 ) (x1,y1)->(x2,y2) (x1,y1)−>(x2,y2)区间的和
代码:
int n;
cin>>n;
while(n-->0){
int x1,y1,x2,y2;
cin>>x1>>y1>>x2>>y2;
int S=sum[x2][y2]-sum[x1-1][y2]-sum[x2][y1-1]+sum[x1-1][y1-1];
cout<<S<<endl;
}