New Year and Domino
They say “years are like dominoes, tumbling one after the other”. But would a year fit into a grid? I don’t think so.
Limak is a little polar bear who loves to play. He has recently got a rectangular grid with h rows and w columns. Each cell is a square, either empty (denoted by ‘.’) or forbidden (denoted by ‘#’). Rows are numbered 1 through h from top to bottom. Columns are numbered 1 through w from left to right.
Also, Limak has a single domino. He wants to put it somewhere in a grid. A domino will occupy exactly two adjacent cells, located either in one row or in one column. Both adjacent cells must be empty and must be inside a grid.
Limak needs more fun and thus he is going to consider some queries. In each query he chooses some rectangle and wonders, how many way are there to put a single domino inside of the chosen rectangle?
题目大意:先给你一个长方形的图,图有 h*w 个方块,每个方块要不是空 ,要不被占,然后问你在一个子图里面两个连续的空方块有多少种连接方式;
二维前缀和很容易想到,但是没想到要横竖分开表示,sumr[][] 表示横着摆的个数,sumc[][] 表示竖着摆的个数;
然后求答案要注意不是一般的二维前缀和求和,要注意边界上的加减问题,画个图就非常明显了;
代码:
#include<bits/stdc++.h>
#define LL long long
#define pa pair<int,int>
#define ls k<<1
#define rs k<<1|1
#define inf 0x3f3f3f3f
using namespace std;
const int N=100100;
const int M=2000100;
const LL mod=1e9+7;
char s[510][510];
LL sumr[510][510],sumc[510][510];
int main(){
int h,w;cin>>h>>w;
for(int i=1;i<=h;i++) scanf("%s",s[i]+1);
for(int i=1;i<=h;i++){
for(int j=1;j<=w;j++){
sumr[i][j]=sumr[i][j-1]+sumr[i-1][j]-sumr[i-1][j-1];
sumc[i][j]=sumc[i][j-1]+sumc[i-1][j]-sumc[i-1][j-1];
if(s[i][j]=='.'){
if(s[i][j-1]=='.') sumr[i][j]++;
if(s[i-1][j]=='.') sumc[i][j]++;
}
}
}
int q;cin>>q;
while(q--){
int r1,c1,r2,c2;
scanf("%d%d%d%d",&r1,&c1,&r2,&c2);
LL ans=sumr[r2][c2]-sumr[r1-1][c2]-sumr[r2][c1]+sumr[r1-1][c1];
ans+=sumc[r2][c2]-sumc[r1][c2]-sumc[r2][c1-1]+sumc[r1][c1-1];
printf("%lld\n",ans);
}
return 0;
}