UVA 11019 矩阵匹配器 二维hash

题目链接:https://vjudge.net/problem/UVA-11019
转自:https://blog.csdn.net/qq_43464645/article/details/90387382
题意:有两个矩阵,求下面得矩阵在上面矩阵出现了多少次。
思路:二维hash。自己规定一个矩阵的hash值就是每行每列的hash值的和。预处理下大矩阵的hash值,用公式hash[l,r]=hash[r]−hash[l−1]∗seed ^r−l+1暴力计算每个小矩阵的hash值。

#include <bits/stdc++.h>
using namespace std;
const int maxn=1e3+5;
const unsigned long long seed=131;
int n,m,x,y,res;
unsigned long long sd[maxn],hash1r[maxn][maxn],hash1l[maxn][maxn],hash2r[maxn][maxn],hash2l[maxn][maxn];
char s[maxn][maxn],p[maxn][maxn];
unsigned long long ans,sum;
void init()
{
    sd[0]=1;
    sd[1]=seed;
    for(int i=2; i<maxn; i++)
    {
        sd[i]=sd[i-1]*seed;
    }
}
int main()
{
    init();
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d",&n,&m);
        for(int i=1; i<=n; i++)
        {
            scanf("%s",s[i]+1);
        }
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=m;j++)
            {
                hash1r[i][j]=hash1r[i][j-1]*seed+s[i][j];
                hash1l[i][j]=hash1l[i-1][j]*seed+s[i][j];
            }
        }
        ans=0;
        res=0;
        scanf("%d%d",&x,&y);
        for(int i=1;i<=x;i++)
        {
            scanf("%s",p[i]+1);
        }
        for(int i=1;i<=x;i++)
        {
            for(int j=1;j<=y;j++)
            {
                hash2r[i][j]=hash2r[i][j-1]*seed+p[i][j];
                hash2l[i][j]=hash2l[i-1][j]*seed+p[i][j];
                if(j==y)
                {
                 ans+=hash2r[i][j];
                }
                if(i==x)
                {
                    ans+=hash2l[i][j];
                }
            }
        }
        for(int i=1;i<=n-x+1;i++)
        {
            for(int j=1;j<=m-y+1;j++)
            {
                sum=0;
                for(int k=i;k<=i+x-1;k++)
                {
                    sum+=hash1r[k][j+y-1]-hash1r[k][j-1]*sd[y];
                }
                for(int k=j;k<=y+j-1;k++)
                {
                    sum+=hash1l[i+x-1][k]-hash1l[i-1][k]*sd[x];
                }
                if(sum==ans)
                    res++;
            }
        }
        printf("%d\n",res);
    }
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值