标签:for long def dig getch poj queue ons 就是
嘟嘟嘟
哈希
刚开始我一直在想二维哈希,但发现如果还是按行列枚举的话会破坏子矩阵的性质。也就是说,这个哈希只能维护一维的子区间的哈希值。
所以我就开了个二维数组\(has_{i, j}\)表示原矩阵\(s_{i, j - q + 1}\)到\(s_{i, j}\)的哈希值,所以这个要用滚动哈希。
滚动哈希就是这样的:\(hash[s_{i, i + m}] = hash[s_{i + 1, j + m + 1}] * base - s_i * base ^ m\)。理解起来就是把\(s_i\)对哈希的贡献减去。
然后用同样的方法算出\(p * q\)矩阵的哈希值。最后逐行比对。
时间复杂度瓶颈在于比对复杂度\(O(n ^ 2 * p)\)。
#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<vector>
#include<stack>
#include<queue>
using namespace std;
#define enter puts("")
#define space putchar(‘ ‘)
#define Mem(a, x) memset(a, x, sizeof(a))
#define rg register
typedef long long ll;
typedef double db;
typedef unsigned long long ull;
const ull bas = 19260817;
const int INF = 0x3f3f3f3f;
const db eps = 1e-8;
const int maxn = 1e3 + 5;
inline ll read()
{
ll ans = 0;
char ch = getchar(), last = ‘ ‘;
while(!isdigit(ch)) last = ch, ch = getchar();
while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - ‘0‘, ch = getchar();
if(last == ‘-‘) ans = -ans;
return ans;
}
inline void write(ll x)
{
if(x < 0) x = -x, putchar(‘-‘);
if(x >= 10) write(x / 10);
putchar(x % 10 + ‘0‘);
}
int n, m, t, p, q;
char tp[maxn];
ull has[maxn][maxn], a[maxn];
bool judge()
{
for(int i = 1; i <= n - p + 1; ++i)
for(int j = q; j <= m; ++j)
{
bool flg = 1;
for(int k = 1; k <= p && flg; ++k)
if(has[i + k - 1][j] != a[k]) flg = 0;
if(flg) return 1;
}
return 0;
}
ull quickpow(ull a, int b)
{
ull ret = 1;
for(; b; b >>= 1, a *= a)
if(b & 1) ret *= a;
return ret;
}
int main()
{
int tcnt = 0;
while(scanf("%d", &n) && n)
{
m = read(); t = read(); p = read(); q = read();
for(int i = 1; i <= n; ++i)
{
scanf("%s", tp + 1);
for(int j = 1; j <= m; ++j)
{
has[i][j] = has[i][j - 1] * bas + tp[j];
if(j >= q + 1) has[i][j] -= quickpow(bas, q) * tp[j - q];
}
}
int ans = 0;
while(t--)
{
for(int i = 1; i <= p; ++i)
{
a[i] = 0;
scanf("%s", tp + 1);
for(int j = 1; j <= q; ++j) a[i] = a[i] * bas + tp[j];
}
if(judge()) ans++;
}
printf("Case %d: %d\n", ++tcnt, ans);
}
return 0;
}
标签:for long def dig getch poj queue ons 就是
原文地址:https://www.cnblogs.com/mrclr/p/10014992.html