二维矩阵匹配+hash模板

题意

1
二维矩阵匹配+hash模板

code

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
66
67
68
69
70
71

#include <algorithm>
#include <cstring>
#include <set>
using namespace std;
typedef unsigned long long ull;
const int MAX_SIZE = 1010;
const int MAX_T = 110;

int N,M,T,P,Q;
char field[MAX_SIZE][MAX_SIZE];
char patterns[MAX_T][MAX_SIZE][MAX_SIZE];
ull has[MAX_SIZE][MAX_SIZE],tmp[MAX_SIZE][MAX_SIZE];
int cas;

void (char a[MAX_SIZE][MAX_SIZE],int n, int m)
{
const ull B1 = 9973;
const ull B2 = 100000007;
ull t1 = 1;
for(int i = 0; i < Q; ++i) t1 *= B1;
for(int i = 0; i < n; ++i){//先把矩阵每行 看成一串字符串进行hash压缩
ull e = 0;
for(int j = 0; j < Q; ++j) e = e * B1 + a[i][j];
for(int j = 0; j + Q <= m; ++j){//滚动hash
tmp[i][j] = e;
if(j + Q < m)
e = e * B1 - t1 * a[i][j] + a[i][j + Q];
}
}
ull t2 = 1;
for(int i = 0; i < P; ++i) t2 *= B2;//在把上面压缩的进行列hash
for(int j = 0; j + Q <= m; ++j){
ull e = 0;
for(int i = 0; i < P; ++i) e = e * B2 + tmp[i][j];
for(int i = 0; i + P <= n; ++i){
has[i][j] = e;
if(i + P < n) e = e * B2 - t2 * tmp[i][j] + tmp[i+P][j];
}
}
}

void solve()
{
multiset<ull> unseen;//用multiset 进行统计
for(int k = 0; k < T; ++k){
compute_hash(patterns[k],P,Q);
unseen.insert(has[0][0]);
}
compute_hash(field,N,M);
for(int i = 0; i + P <= N; i++)
for(int j = 0; j + Q <= M; j++)
unseen.erase(has[i][j]);
int ans=T-unseen.size();
printf("Case %d: %dn",++cas ,ans);
}

int main(void)
{
while(scanf("%d%d%d%d%d",&N,&M,&T,&P,&Q) && (N+M+T+P+Q)){
for(int i = 0; i < N; i++)
scanf("%s",field[i]);
for(int i = 0; i < T; i++)
{
for(int j = 0; j < P; j++)
scanf("%s",patterns[i][j]);
}
solve();
}
return 0;
}