UVA11019 Matrix Matcher
传送
二维哈希。
初始化和查询的时候仿照二维前缀和。只不过行和列要分别有两个不同的哈希值。
然而我写的取模哈希不知道为啥它WA了,改成自然溢出的过了……
代码放上,怕忘。
#include<cstdio>
#include<cstring>
#include<cctype>
using namespace std;
#define enter puts("")
#define In inline
typedef long long ll;
typedef unsigned long long ull;
const int maxn = 1e3 + 5;
const ull BAS1 = 233333;
const ull BAS2 = 183203;
In ll read()
{
ll ans = 0;
char ch = getchar(), las = ' ';
while(!isdigit(ch)) las = ch, ch = getchar();
while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar();
if(las == '-') ans = -ans;
return ans;
}
In void write(ll x)
{
if(x < 0) x = -x, putchar('-');
if(x >= 10) write(x / 10);
putchar(x % 10 + '0');
}
int n, m, x, y;
char s[maxn][maxn], s2[maxn][maxn];
ull p1[maxn], p2[maxn];
ull h[maxn][maxn], h2[maxn][maxn];
In void hash_init(char s[maxn][maxn], ull h[maxn][maxn], int n, int m)
{
for(int i = 1; i <= n; ++i)
for(int j = 1; j <= m; ++j)
h[i][j] = h[i - 1][j] * BAS1 + h[i][j - 1] * BAS2 - h[i - 1][j - 1] * BAS1 * BAS2 + s[i][j];
}
In ull H(int x1, int y1, int x2, int y2)
{
return h[x2][y2] - h[x2][y1 - 1] * p2[y] - h[x1 - 1][y2] * p1[x] + h[x1 - 1][y1 - 1] * p1[x] * p2[y];
}
int main()
{
p1[0] = p2[0] = 1;
for(int i = 1; i < maxn; ++i) p1[i] = p1[i - 1] * BAS1, p2[i] = p2[i - 1] * BAS2;
int T = read();
while(T--)
{
n = read(), m = read();
for(int i = 1; i <= n; ++i) scanf("%s", s[i] + 1);
x = read(), y = read();
for(int i = 1; i <= x; ++i) scanf("%s", s2[i] + 1);
hash_init(s, h, n, m), hash_init(s2, h2, x, y);
int ans = 0;
for(int i = 1; i <= n - x + 1; ++i)
for(int j = 1; j <= m - y + 1; ++j)
if(H(i, j, i + x - 1, j + y - 1) == h2[x][y]) ++ans;
write(ans), enter;
}
return 0;
}