Description
给定一个M行N列的01矩阵,以及Q个A行B列的01矩阵,你需要求出这Q个矩阵哪些在原矩阵中出现过。
所谓01矩阵,就是矩阵中所有元素不是0就是1。
Input
输入文件的第一行为M、N、A、B,参见题目描述。
接下来M行,每行N个字符,非0即1,描述原矩阵。
接下来一行为你要处理的询问数Q。
接下来Q个矩阵,一共Q*A行,每行B个字符,描述Q个01矩阵。
Output
你需要输出Q行,每行为0或者1,表示这个矩阵是否出现过,0表示没有出现过,1表示出现过。
Sample Input
3 3 2 2
111
000
111
3
11
00
11
11
00
11
Sample Output
1
0
1
HINT
对于100%的实际测试数据,M、N ≤ 1000,Q = 1000
对于40%的数据,A = 1。
对于80%的数据,A ≤ 10。
对于100%的数据,A ≤ 100。
以下是摘自一位网络大神的代码,理解下就是了。
Source
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#define UI unsigned int
#define MAXN 1010
#define P 77171
#define base1 9804799
#define base2 9983543
using namespace std;
int n,m,A,B,Q;
UI a[MAXN][MAXN],b[MAXN][MAXN],pow1[MAXN],pow2[MAXN],HASH;
int hash[P],top;
struct list
{
UI num;
list *next;
}s[MAXN*MAXN];
void Insert_hash(UI x)
{
int t=x%P;
s[++top].num=x;s[top].next=&s[hash[t]];hash[t]=top;
}
bool find(UI x)
{
int t=x%P;
for (list *i=&s[hash[t]];i;i=i->next)
if (i->num==x) return 1;
return 0;
}
int main()
{
scanf("%d%d%d%d",&m,&n,&A,&B);pow1[0]=pow2[0]=1;
for (int i=1;i<=m;i++)
for (int j=1;j<=n;j++) scanf("%1d",&a[i][j]);
for (int i=1;i<=max(n,m);i++) pow1[i]=pow1[i-1]*base1,pow2[i]=pow2[i-1]*base2;
for (int i=1;i<=m;i++)
for (int j=1;j<=n;j++) a[i][j]+=a[i-1][j]*base1;
for (int i=1;i<=m;i++)
for (int j=1;j<=n;j++) a[i][j]+=a[i][j-1]*base2;
for (int i=A;i<=m;i++)
for (int j=B;j<=n;j++)
{
HASH=a[i][j];HASH-=a[i-A][j]*pow1[A];HASH-=a[i][j-B]*pow2[B];HASH+=a[i-A][j-B]*pow1[A]*pow2[B];
Insert_hash(HASH);
}
scanf("%d",&Q);
while (Q--)
{
for (int i=1;i<=A;i++)
for (int j=1;j<=B;j++) scanf("%1d",&b[i][j]);
for (int i=1;i<=A;i++)
for (int j=1;j<=B;j++) b[i][j]+=b[i-1][j]*base1;
for (int i=1;i<=A;i++)
for (int j=1;j<=B;j++) b[i][j]+=b[i][j-1]*base2;
puts(find(b[A][B])?"1":"0");
}
}