求助站外题,二维哈希,悬赏关注
  • 板块学术版
  • 楼主dyyzy
  • 当前回复2
  • 已保存回复2
  • 发布时间2023/7/6 21:06
  • 上次更新2023/11/3 11:16:34
查看原帖
求助站外题,二维哈希,悬赏关注
461012
dyyzy楼主2023/7/6 21:06

acwing156

#include<iostream>
#include<cstring>
#include<cstdio>
#define ull unsigned long long
using namespace std;
const int N=1e3+10;
const int P=1331;
const int Q=131;
ull ha[N][N],hsh[N][N];
int main(){
	int n,m,a,b;
	cin>>n>>m>>a>>b;
	for(int i=1;i<=n;++i){
		string s;cin>>s;
		for(int j=1;j<=m;++j)
			ha[i][j]=ha[i][j-1]*P+(s[j-1]-'0'+1);
	}
	for(int i=1;i<=n;++i)
		for(int j=1;j<=m;++j)
			ha[i][j]+=ha[i-1][j]*Q;
	int q;cin>>q;
	while(q--){
		bool flag=false;
		memset(hsh,0,sizeof(hsh));
		for(int i=1;i<=a;++i){
			string s;cin>>s;
			for(int j=1;j<=b;++j)
				hsh[i][j]=hsh[i][j-1]*P+(s[j-1]-'0'+1);
		}
		for(int i=1;i<=a;++i)
			for(int j=1;j<=b;++j)
				hsh[i][j]+=hsh[i-1][j]*Q;
//		cout<<hsh[a][b]<<'\n';
		for(int i=1;i<=n-a+1;++i)
			for(int j=1;j<=m-b+1;++j)
				if(ha[i+a-1][j+b-1]-ha[i-1][j+b-1]*P*(b+1)-ha[i+a-1][j-1]*Q*(a+1)+ha[i-1][j-1]*P*(b+1)*Q*(a+1)==hsh[a][b]) flag=true;
		if(flag) cout<<"1\n";
		else cout<<"0\n";
	}
}
2023/7/6 21:06
加载中...