Good Bye 2015 C

题意:计算给定矩形面积(r1,c1),(r2,c2)内长度为2的有多少个?向右或向下计算。

思路:预处理字符。分别向右和向下处理。注意边界情况,可能算多了。用容斥原理计算长度为二的单位。

 1 #include<iostream>
 2 #include<string>
 3 #include<algorithm>
 4 #include<cstdlib>
 5 #include<cstdio>
 6 #include<set>
 7 #include<map>
 8 #include<vector>
 9 #include<cstring>
10 #include<stack>
11 #include<cmath>
12 #include<queue>
13 #include <bits/stdc++.h>
14 using namespace std;
15 #define INF 0x3f3f3f3f
16 #define ll long long
17 #define clc(a,b) memset(a,b,sizeof(a))
18 const int maxn=1000000;
19 
20 char str[510][510];
21 int persum[510][510];
22 int rightt[510][510];
23 int down[510][510];
24 int n,m,r1,r2,c1,c2;
25 
26 void init()
27 {
28     for(int i=1; i<=n; i++)
29     {
30         for(int j=1; j<=m; j++)
31         {
32             if(str[i][j]=='.'&&str[i][j+1]=='.')
33             {
34                 rightt[i][j]=1;
35                 persum[i][j]++;
36             }
37             if(str[i][j]=='.'&&str[i+1][j]=='.')
38             {
39                 down[i][j]=1;
40                 persum[i][j]++;
41             }
42             persum[i][j]+=persum[i-1][j]+persum[i][j-1]-persum[i-1][j-1];
43         }
44     }
45 }
46 
47 int main()
48 {
49 //    freopen("in.txt","r",stdin);
50     while(~scanf("%d%d",&n,&m))
51     {
52         int q;
53         clc(persum,0);
54         clc(rightt,0);
55         clc(down,0);
56         for(int i=1; i<=n; i++)
57             scanf("%s",str[i]+1);
58         init();
59         cin>>q;
60         while(q--)
61         {
62             cin>>r1>>c1>>r2>>c2;
63             int cnt=0;
64             cnt=persum[r2][c2]-persum[r2][c1-1]-persum[r1-1][c2]+persum[r1-1][c1-1];
65             for(int i=r1; i<=r2; i++)
66                 if(rightt[i][c2]) cnt--;
67             for(int j=c1; j<=c2; j++)
68                 if(down[r2][j])cnt--;
69             cout<<cnt<<endl;
70         }
71     }
72     return 0;
73 }
View Code
原文地址:https://www.cnblogs.com/ITUPC/p/5154815.html