UVA - 11019 Matrix Matcher hash+KMP

Posted Meek

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UVA - 11019 Matrix Matcher hash+KMP相关的知识,希望对你有一定的参考价值。

题目链接:https://vjudge.net/problem/UVA-11019

题解:

  赶着回寝室

  明天写题解

#include<bits/stdc++.h>
using namespace std;
#pragma comment(linker, "/STACK:102400000,102400000")
#define ls i<<1
#define rs ls | 1
#define mid ((ll+rr)>>1)
#define pii pair<int,int>
#define MP make_pair
typedef long long LL;
typedef unsigned long long ULL;
const long long INF = 1e18+1LL;
const double pi = acos(-1.0);
const int N = 2e3+10, M = 1e3+20,inf = 2e9;

const ULL mod = 10000019ULL;
int n,m,x,y,T,fail[N];
char a[N][N],b[N][N];
ULL has[N][N],mp[N][N],s[N],t[N],sqr[N];
void build_fail() {
    int j = 0;
    memset(fail,0,sizeof(fail));
    for(int i = 2; i <= y; ++i) {
        while(j&&s[i]!=s[j+1]) j = fail[j];
        if(s[i] == s[j+1]) j++;
        fail[i] = j;
    }
}
int kmp() {
    int ret = 0, j = 0;
    for(int i = 1; i <= n; ++i) {
        while(j&&s[j+1]!=t[i]) j = fail[j];
        if(s[j+1] == t[i]) j++;
        if(j == x) {
            ret += 1;
            j = fail[j];
        }
    }
    return ret;
}
int main() {
    sqr[0] = 1;
    for(int i = 1; i < N; ++i) sqr[i] = sqr[i-1] * mod;
    scanf("%d",&T);
    while(T--) {
        scanf("%d%d",&n,&m);
        for(int i = 1; i <= n; ++i) scanf("%s",a[i]+1);
        scanf("%d%d",&x,&y);
        for(int i = 1; i <= x; ++i) scanf("%s",b[i]+1);
        if(n < x || m < y) {
            puts("0");
            continue;
        }
        for(int i = 1; i <= n; ++i) {
            for(int j = 1; j <= m; ++j)
                has[i][j] = has[i][j - 1] * mod + a[i][j];
        }
        for(int i = 1; i <= x; ++i) {
            ULL now = 0, ps = 1;
            for(int j = 1; j <= y; ++j) {
                now = now * mod + b[i][j];
            }
            s[i] = now;
        }
        build_fail();
        int ans = 0;
        for(int j = 1; j <= m - y + 1; ++j) {
            for(int i = 1; i <= n; ++i) {
                int l = j, r = j + y - 1;
                ULL now = has[i][r] - has[i][l-1] * sqr[r - l + 1];
                t[i] = now;
            }
            ans += kmp();
        }
        printf("%d\n",ans);
    }
    return 0;
}

 

以上是关于UVA - 11019 Matrix Matcher hash+KMP的主要内容,如果未能解决你的问题,请参考以下文章

UVA11019 Matrix Matcher

UVA11019 Matrix Matcher

UVA 11019 Matrix Matcher 二维的字符串匹配 ac自动机

UVA 11149 Power of Matrix

UVa 11082 - Matrix Decompressing(最大流)

UVA - 11992:Fast Matrix Operations