#include<stdio.h> #include<string.h> typedef unsigned long long ULL; const ULL Base1 = 10000007; const ULL Base2 = 100000007; int test,n,m,x,y; ULL ans; char s[2005][2005],a[2005][2005]; ULL hash; ULL temp[2005][2005],Temp[2005][2005]; ULL Gethash() { ULL c,d = 0; for(int i = 0; i < x; ++i) { c = 0; for(int j = 0; j < y; ++j) { c = c*Base1 + a[i][j]; } d = d * Base2 + c; } return d; } void GetAns() {//把矩阵中的hash算出来,每个子矩阵的。 ULL t,a; // 算的时候与目标hash匹配判断一下.... t = 1; for(int i = 0; i < y; ++i) t *= Base1; for(int i = 0; i < n; ++i) { a = 0; for(int j = 0; j < y; ++j) a = a*Base1 + s[i][j]; temp[i][y-1] = a; for(int j = y; j < m; ++j) { temp[i][j]=temp[i][j-1]*Base1-s[i][j-y]*t+s[i][j]; } } t = 1; for(int i = 0; i < x; ++i) t *= Base2; for(int i = y-1; i < m; ++i) { a = 0; for(int j = 0; j < x; ++j) a = a*Base2 + temp[j][i]; Temp[x-1][i] = a; if(a == hash) ans++; for(int j = x; j < n; ++j) { Temp[j][i] = Temp[j-1][i]*Base2 - temp[j-x][i] * t + temp[j][i]; if(Temp[j][i]== hash) ans++; } } } int main() { while(scanf("%d%d%d%d",&x,&y,&n,&m)!= EOF) { //scanf("%d%d",&n,&m); for(int i = 0; i < x; ++i) scanf("%s",a[i]); //scanf("%d%d",&n,&m); for(int i = 0; i < n; ++i) scanf("%s",s[i]); hash = Gethash(); ans = 0; GetAns(); printf("%llu\n",ans); } return 0; }
贴个模板,防止忘记了..