# BZOJ2351 [BeiJing2011]Matrix 解题报告【数据结构】【Hash】

Description

Input

Output

Sample Input
3 3 2 2
111
000
111
3
11
00
11
11
00
11
Sample Output
1
0
1
HINT

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
const int N=1000;
const int BASE1=10016957;
const int BASE2=10016959;
const int Mod=10100;
using namespace std;
struct abcd{
unsigned num;
int next;
}table[N*N+5];
int m,n,a,b,q;
unsigned int sum[N+5][N+5],power1[N+5],power2[N+5];
int hash_table[Mod],tot;
void Hash(unsigned int x)//插入新的hash值
{
int pos=x%Mod;
table[++tot].num=x;
table[tot].next=hash_table[pos];
hash_table[pos]=tot;
}
bool Get_Hash(unsigned int x)//查询其在hash表中的存在
{
int pos=x%Mod;
for(int i=hash_table[pos];i;i=table[i].next)
if(table[i].num==x)return true;
return false;
}
int main()
{
scanf("%d%d%d%d",&m,&n,&a,&b);
for(int i=1;i<=m;i++)
for(int j=1;j<=n;j++)
scanf("%1d",&sum[i][j]);
for(int i=1;i<=m;i++)
for(int j=1;j<=n;j++)
sum[i][j]+=sum[i-1][j]*BASE1;//行hash
for(int i=1;i<=m;i++)
for(int j=1;j<=n;j++)
sum[i][j]+=sum[i][j-1]*BASE2;//列hash
power1[0]=power2[0]=1;
for(int i=1;i<=N;i++)
power1[i]=power1[i-1]*BASE1,power2[i]=power2[i-1]*BASE2;//打表打出base的i次幂
for(int i=a;i<=m;i++)
for(int j=b;j<=n;j++)
{
unsigned int temp=sum[i][j]
-sum[i-a][j]*power1[a]
-sum[i][j-b]*power2[b]
+sum[i-a][j-b]*power1[a]*power2[b];//对前缀hash值加加减减得到部分hash
Hash(temp);
}
for(scanf("%d",&q);q;q--)
{
for(int i=1;i<=a;i++)
for(int j=1;j<=b;j++)
scanf("%1d",&sum[i][j]);
for(int i=1;i<=a;i++)
for(int j=1;j<=b;j++)
sum[i][j]+=sum[i-1][j]*BASE1;
for(int i=1;i<=a;i++)
for(int j=1;j<=b;j++)
sum[i][j]+=sum[i][j-1]*BASE2;
unsigned int temp=sum[a][b];
if(Get_Hash(temp))puts("1");
else puts("0");
}
return 0;
}