UVa 11019 Matrix Matcher - Hash

时间:2023-03-09 03:51:00
UVa 11019 Matrix Matcher - Hash

题目传送门

  快速的vjudge传送门

  快速的UVa传送门

题目大意

  给定两个矩阵S和T,问T在S中出现了多少次。

  不会AC自动机做法。

  考虑一维的字符串Hash怎么做。

  对于一个长度为$l$的字符串$s$,它的Hash值$hash(s) = \sum_{i = 1}^{l}x^{l - i}s_{i}$。

  对于二维的情况,我们就取两个基,$x, y$,对于一个$n\times m$的矩阵$A$的Hash值可以表示为

$hash(A) = \sum_{i = 1}^{n}\sum_{j = 1}^{m}x^{n - i}y^{m - j}a_{ij}$

  然后以记录$S$的左上角的左上角的所有子矩阵的hash值(这个可以$O(1)$转移)。询问一个子矩阵的hash值,就可以$O(1)$回答。

  接下来就很简单了。枚举每个位置判断是否匹配。

Code

 /**
* UVa
* Problem#11019
* Accepted
* Time: 50ms
*/
#include <iostream>
#include <cstdlib>
#include <cstdio>
using namespace std;
typedef bool boolean; const unsigned int hash1 = , hash2 = ;
const int N = , M = ; int p1[N], p2[N];
int m, n, x, y;
char S[N][N], T[M][M];
unsigned int hs[N][N]; inline void prepare() {
p1[] = , p2[] = ;
for (int i = ; i < N; i++)
p1[i] = p1[i - ] * hash1;
for (int i = ; i < N; i++)
p2[i] = p2[i - ] * hash2;
} inline void init() {
scanf("%d%d", &n, &m);
for (int i = ; i <= n; i++)
scanf("%s", S[i] + );
scanf("%d%d", &x, &y);
for (int i = ; i <= x; i++)
scanf("%s", T[i] + );
} inline void solve() {
for (int i = ; i <= n; i++)
for (int j = ; j <= m; j++) {
hs[i][j] = hs[i - ][j - ] * hash1 * hash2 + (hs[i - ][j] - hs[i - ][j - ] * hash2) * hash1 + (hs[i][j - ] - hs[i - ][j - ] * hash1) * hash2 + S[i][j];
} /* unsigned int s1 = 0;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
s1 += S[i][j] * p1[n - i] * p2[m - j]; cerr << s1 << " " << (97u * 200379 * 211985 + 98u * 200379 + 98u * 211985 + 97) << " " << hs[2][2] << endl;*/ int rt = ;
unsigned int s = , c;
for (int i = ; i <= x; i++)
for (int j = ; j <= y; j++)
s += T[i][j] * p1[x - i] * p2[y - j];
// cerr << s << endl;
for (int i = x; i <= n; i++)
for (int j = y; j <= m; j++) {
c = hs[i][j] - hs[i - x][j - y] * p1[x] * p2[y] - (hs[i][j - y] - hs[i - x][j - y] * p1[x]) * p2[y] - (hs[i - x][j] - hs[i - x][j - y] * p2[y]) * p1[x];
if (s == c)
rt++;
}
printf("%d\n", rt);
} int kase;
int main() {
prepare();
scanf("%d", &kase);
while (kase--) {
init();
solve();
}
return ;
}