跳到正文

个人记录

二维hash

KRIS_ALLEN约 3 分钟
原文
文章信息与版本

文章信息

发布
2022年3月1日
收录
2026年9月3日
更新
2026年11月21日
篇幅
约 3 分钟

版本

  1. v1当前

在设定数值没有发生哈希冲突时可以用来做字符串的快速比较。与一维hash并没有本质区别,只不过把二维的数据参与进hash运算

C++
#include<iostream>  
#include<algorithm>
#include<cstdio>
#define ll long long int
  
using namespace std;
  
const int N=1009;
  
ll n,m,a,b,base1=131,base2=233,b1[N],b2[N],h[N][N],ans[N*N],lp[N][N];
  
char s[N][N];
  
ll getsum(int i,int j,int x,int y)
  
{
	return h[x][y]-h[x][j-1]*b1[y-j+1]-h[i-1][y]*b2[x-i+1]+h[i-1][j-1]*b1[y-j+1]*b2[x-i+1];
}
int main()
{
	int cnt=0;
	scanf("%lld%lld%lld%lld",&n,&m,&a,&b);
	getchar();
	b1[0]=b2[0]=1;
	for(int i=1;i<=1000;i++)
	{
		b1[i]=b1[i-1]*base1;
		b2[i]=b2[i-1]*base2;
	}
	for(int i=1;i<=n;i++)
	{
		scanf("%s",s[i]+1);
		for(int j=1;j<=m;j++)
		{
			h[i][j]=h[i][j-1]*base1+s[i][j]-'0';
		}
	}
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			h[i][j]=h[i-1][j]*base2+h[i][j];
		}		
	}
	for (int i = 1; i <= n - a + 1; ++i)
        for (int j = 1; j <= m - b + 1; ++j)
            ans[cnt++] = getsum(i, j, i + a - 1, j + b - 1);
	int q;
	sort(ans,ans+cnt);
	scanf("%d",&q);
	getchar();
	while(q--)
	{
		for(int i=1;i<=a;i++)
		{
			scanf("%s",s[i]+1);
			for(int j=1;j<=b;j++)
			{
				lp[i][j]=lp[i][j-1]*base1+s[i][j]-'0';
			}
		}
		for(int i=1;i<=a;i++)
		{
			for(int j=1;j<=b;j++)
			{
				lp[i][j]=lp[i-1][j]*base2+lp[i][j];
			}
		}
		cout<<(binary_search(ans, ans + cnt, lp[a][b]) ? "1" : "0")<<endl;
	}
	return 0;
}
原文