题目链接:http://codeforces.com/contest/611/problem/C
解题思路:
分别对矩阵横竖遍历,满足条件则加1,不满足则不变,先将整个矩阵都标记完,然后只要输出起点和终点数值的差值就行。有点动态规划的感觉。
#include<iostream> #include<string> #include<cstdio> using namespace std; const int Max = 550; char s[Max][Max]; int m,n,i,mp[Max][Max],s_x,s_y,e_x,e_y,j,na[Max][Max],nb[Max][Max]; int main() { cin>>m>>n; for(i=1;i<=m;i++) scanf("%s",s[i]+1); for(i=1;i<=m;i++){ for(j=1;j<=n;j++){ if(s[i][j]=='.') mp[i][j] = 1; else mp[i][j] = 0; } } for(i=1;i<=m;i++){ for(j=1;j<=n;j++){ if(mp[i][j]&&mp[i][j+1]) na[i][j] = na[i][j-1] + 1; else na[i][j] = na[i][j-1]; } } for(i=1;i<=n;i++){ for(j=1;j<=m;j++){ if(mp[j][i]&&mp[j+1][i]) nb[j][i] = nb[j-1][i] + 1; else nb[j][i] = nb[j-1][i]; } } int t; cin>>t; while(t--){ int ans = 0; cin>>s_x>>s_y>>e_x>>e_y; for(i=s_x;i<=e_x;i++) ans+=na[i][e_y-1] - na[i][s_y-1]; for(i=s_y;i<=e_y;i++) ans+=nb[e_x-1][i] - nb[s_x-1][i]; cout<<ans<<endl; } return 0; } /*5 8 ....#..# .#...... ##.#.... ##..#.## ........ 4 1 1 2 3 4 1 4 1 1 2 4 5 2 5 5 8*/