题意:给出一个N*M的大矩阵。在给出T个P*Q的小矩阵,问有多少个小矩阵在大矩阵中出现过。
思路:二维hash。算出整个矩阵的所有的P*Q小矩阵的hash值,同时求出目标矩阵的hash值,判断该值是否出现即可。
复杂度:N * M * K
代码如下:
#include <cstdio>
#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 compute_hash(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){
ull e = 0;
for(int j = 0; j < Q; ++j) e = e * B1 + a[i][j];
for(int j = 0; j + Q <= m; ++j){
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;
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;
compute_hash(field,N,M);
for(int i = 0; i + P <= N; ++i)
for(int j = 0; j + Q <= M; ++j)
unseen.insert(has[i][j]);
int cnt = 0;
for(int k = 0; k < T; ++k){
compute_hash(patterns[k],P,Q);
if(unseen.count(has[0][0])) cnt++;
}
printf("Case %d: %d\n",++cas ,cnt);
}
int main(void)
{
//freopen("input.txt","r",stdin);
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;
}