题目大意:给定一个二维矩阵,求出现次数最多的a*b的子矩阵
二维Hash,只要记住横纵的BASE不能相同就可以,爱怎么搞怎么搞
一开始写的自然溢出 结果OLE 以为是自然溢出被卡掉了于是写了双取模…… 结果还是OLE
最后发现尼玛这题读入坑爹……字符串里有空格不说,满满的不可见字符是咋回事……
记住不要用scanf读入……可以用gets,或者fread,注意要把一开始的回车过滤掉
getchar读进来全是错的 不知道怎么回事……
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #define M 1010 #define BASE1 2591 #define BASE2 2593 #define MOD1 1000000007 #define MOD2 1000000009 using namespace std; typedef long long ll; int m,n,a,b,ans_time; char s[M][M]; ll sum1[M][M],sum2[M][M],ans1,ans2,BASE1_a[3]={0,1,1},BASE2_b[3]={0,1,1}; namespace Hash_Table{ struct list{ ll hash_value1,hash_value2; int times; list *next; list(ll _,ll __,list *___): hash_value1(_),hash_value2(__),times(0),next(___) {} }*head[1001001]; inline int& Hash(ll hash1,ll hash2) { list *temp; int x=hash1*hash2%1001001; for(temp=head[x];temp;temp=temp->next) if(temp->hash_value1==hash1&&temp->hash_value2==hash2) return temp->times; return head[x]=new list(hash1,hash2,head[x]),head[x]->times; } } void Output() { int i,j,k,l; for(i=a;i<=m;i++) for(j=b;j<=n;j++) { ll hash1=((sum1[i][j] -sum1[i-a][j]*BASE1_a[1] -sum1[i][j-b]*BASE2_b[1] +sum1[i-a][j-b]*BASE1_a[1]%MOD1*BASE2_b[1] )%MOD1+MOD1)%MOD1; ll hash2=((sum2[i][j] -sum2[i-a][j]*BASE1_a[2] -sum2[i][j-b]*BASE2_b[2] +sum2[i-a][j-b]*BASE1_a[2]%MOD2*BASE2_b[2] )%MOD2+MOD2)%MOD2; if(hash1==ans1&&hash2==ans2) { for(k=i-a+1;k<=i;k++,puts("")) for(l=j-b+1;l<=j;l++) putchar(s[k][l]); return ; } } } void Find_Position() { int i,j; for(i=a;i<=m;i++) for(j=b;j<=n;j++) { ll hash1=((sum1[i][j] -sum1[i-a][j]*BASE1_a[1] -sum1[i][j-b]*BASE2_b[1] +sum1[i-a][j-b]*BASE1_a[1]%MOD1*BASE2_b[1] )%MOD1+MOD1)%MOD1; ll hash2=((sum2[i][j] -sum2[i-a][j]*BASE1_a[2] -sum2[i][j-b]*BASE2_b[2] +sum2[i-a][j-b]*BASE1_a[2]%MOD2*BASE2_b[2] )%MOD2+MOD2)%MOD2; if(hash1==ans1&&hash2==ans2) printf("%d %d\n",i-a+1,j-b+1); } } int main() { int i,j; scanf("%d %d\n",&m,&n); for(i=1;i<=m;i++) { fread(s[i]+1,n+1,1,stdin); for(j=1;j<=n;j++) sum1[i][j]=sum2[i][j]=s[i][j]; } for(i=1;i<=m;i++) for(j=1;j<=n;j++) sum1[i][j]=(sum1[i][j]+sum1[i-1][j]*BASE1)%MOD1, sum2[i][j]=(sum2[i][j]+sum2[i-1][j]*BASE1)%MOD2; for(i=1;i<=m;i++) for(j=1;j<=n;j++) sum1[i][j]=(sum1[i][j]+sum1[i][j-1]*BASE2)%MOD1, sum2[i][j]=(sum2[i][j]+sum2[i][j-1]*BASE2)%MOD2; cin>>a>>b; cout<<a<<' '<<b<<endl; for(i=1;i<=a;i++) { BASE1_a[1]*=BASE1;BASE1_a[1]%=MOD1; BASE1_a[2]*=BASE1;BASE1_a[2]%=MOD2; } for(j=1;j<=b;j++) { BASE2_b[1]*=BASE2;BASE2_b[1]%=MOD1; BASE2_b[2]*=BASE2;BASE2_b[2]%=MOD2; } for(i=a;i<=m;i++) for(j=b;j<=n;j++) { ll hash1=((sum1[i][j] -sum1[i-a][j]*BASE1_a[1] -sum1[i][j-b]*BASE2_b[1] +sum1[i-a][j-b]*BASE1_a[1]%MOD1*BASE2_b[1] )%MOD1+MOD1)%MOD1; ll hash2=((sum2[i][j] -sum2[i-a][j]*BASE1_a[2] -sum2[i][j-b]*BASE2_b[2] +sum2[i-a][j-b]*BASE1_a[2]%MOD2*BASE2_b[2] )%MOD2+MOD2)%MOD2; int& val=Hash_Table::Hash(hash1,hash2); if(++val>ans_time) ans_time=val,ans1=hash1,ans2=hash2; } Output(); cout<<ans_time<<endl; Find_Position(); return 0; }