Problem H
Matrix Matcher
Input: Standard Input
Output: Standard Output
Given an N * M matrix, your task is to find the number of occurences of an X * Y pattern.
Input
The first line contains a single integer t(t ≤ 15), the number of test cases.
For each case, the first line contains two integers N and M (N, M ≤ 1000). The next N lines contain M characters each.
The next line contains two integers X and Y (X, Y ≤ 100). The next X lines contain Y characters each.
Output
For each case, output a single integer in its own line, the number of occurrences.
Sample Input Output for Sample Input
2 1 1 x 1 1 y 3 3 abc bcd cde 2 2 bc cd | 0 2
|
题意:找到在n*m的A中有多少个x*y的B。
思路:先用哈希处理B把每一列当做一个数,然后用KMP处理,对于A中,每次处理一行,处理n-x+1次,每次对A的x行也哈希一次,然后利用KMP的方式去跟B的比较,找到相同的。初学KMP,引见的同学代码。
AC代码如下:
#include<cstdio>
#include<cstring>
using namespace std;
int t,n,m,x,y,ans;
unsigned long long hash[1010][1010],mi[1010],p[1010],q[1010],f[1010];
char s[300];
void getfail()
{ int i,j=0;
memset(f,0,sizeof(f));
for(i=2;i<=y;i++)
{ while(j && p[i]!=p[j+1])
j=f[j];
if(p[i]==p[j+1])
j++;
f[i]=j;
}
}
void find(int pos)
{ int i,j=0;
for(i=1;i<=m;i++)
q[i]=hash[pos+x][i]-hash[pos][i]*mi[x];
for(i=1;i<=m;i++)
{ while(j && q[i]!=p[j+1])
j=f[j];
if(q[i]==p[j+1])
j++;
if (j==y)
{ ans++;
j=f[j];
}
}
}
int main()
{ int i,j;
scanf("%d",&t);
while(t--)
{ scanf("%d%d",&n,&m);
memset(p,0,sizeof(p));
mi[0]=1;ans=0;
for(i=1;i<=n;i++)
{ scanf("%s",s+1);
for(j=1;j<=m;j++)
hash[i][j]=hash[i-1][j]*2333+s[j];
mi[i]=mi[i-1]*2333;
}
scanf("%d%d",&x,&y);
for(i=1;i<=x;i++)
{ scanf("%s",s+1);
for(j=1;j<=y;j++)
p[j]=p[j]*2333+s[j];
}
getfail();
for(i=0;i<=n-x;i++)
find(i);
printf("%d\n",ans);
}
}