1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| #include<bits/stdc++.h> using namespace std; #define rep(i,a,b) for(int i=a,i##end=b;i<=i##end;++i) #define drep(i,a,b) for(int i=a,i##end=b;i>=i##end;--i)
const int N=1e3+10,INF=1e9+10; const int dx[]={0,0,1,-1},dy[]={1,-1,0,0};
int n,m,q; char A[N][N]; int vis[N*N],I[N][N],E[4][N][N],S[N][N];
int B[N][N],C[N][N]; int X[N*N],Y[N*N],cnt;
void dfs(int x,int y){ I[x][y]=cnt; rep(i,0,3) if(E[x][y][i]) { int x1=x+dx[i],y1=y+dy[i]; if(!x1 || !y1||x1>=n || y1>=m || I[x1][y1]) continue; dfs(x1,y1); } } int Sum(const int A[N][N],int x1,int y1,int x2,int y2){ x1--,y1--; return A[x2][y2]-A[x1][y2]-A[x2][y1]+A[x1][y1]; }
int main(){ scanf("%d%d%d",&n,&m,&q); rep(i,1,n) scanf("%s",A[i]+1); rep(i,1,n) rep(j,1,m) { E[0][i][j-1]=E[1][i][j]=A[i][j]!=A[i+1][j]; E[2][i-1][j]=E[3][i][j]=A[i][j]!=A[i][j+1]; if(A[i-1][j]==A[i][j]) B[i][j]++; if(A[i][j]==A[i][j-1]) C[i][j]++; } rep(i,1,n-1) rep(j,1,m-1) if(!I[i][j]) { X[++cnt]=i,Y[cnt]=j,vis[cnt]=q+1; dfs(i,j),S[i][j]++; } rep(i,1,n) rep(j,1,m) { B[i][j]+=B[i-1][j]+B[i][j-1]-B[i-1][j-1]; C[i][j]+=C[i-1][j]+C[i][j-1]-C[i-1][j-1]; S[i][j]+=S[i-1][j]+S[i][j-1]-S[i-1][j-1]; } while(q--) { int lx,ly,rx,ry; scanf("%d%d%d%d",&lx,&ly,&rx,&ry); int V=(rx-lx+1)*(ry-ly+1); int E=Sum(B,lx+1,ly,rx,ry)+Sum(C,lx,ly+1,rx,ry); int F=Sum(S,lx,ly,rx-1,ry-1); auto Check=[&](int i){ if(vis[i]!=q && lx<=X[i] && X[i]<rx && ly<=Y[i] && Y[i]<ry) vis[i]=q,F--; }; rep(i,lx,rx-1) { if(::E[0][i][ry-1]) Check(I[i][ry-1]); if(::E[1][i][ly]) Check(I[i][ly]); } rep(i,ly,ry-1) { if(::E[2][rx-1][i]) Check(I[rx-1][i]); if(::E[3][lx][i]) Check(I[lx][i]); } printf("%d\n",V-E+F); } }
|