題意:給出兩個矩陣,求最大重合。
做出兩個矩陣的hash以後二分最大正方形的邊長,基礎hash。
模數不好設,用自然溢出就好。
#include<cstdio>
#include<algorithm>
#include<cstring>
#define fo(i,a,b) for(int i=a;i<=b;i++)
#define fd(i,a,b) for(int i=a;i>=b;i--)
using namespace std;
typedef long long ll;
const int mo=2333333;
int n;
ll hash1[55][55],hash2[55][55];
ll bin[55],tmp[100005];
int mp1[55][55],mp2[55][55];
inline int calc1(int x,int y,int l)
{
ll v=1;
fo(i,x,x+l-1)v=(v*1789+hash1[i][y+l-1]-hash1[i][y-1]*bin[l]);
return v;
}
inline int calc2(int x,int y,int l)
{
ll v=1;
fo(i,x,x+l-1)v=(v*1789+hash2[i][y+l-1]-hash2[i][y-1]*bin[l]);
return v;
}
bool pd(int x)
{
int tot=0;
fo(i,1,n-x+1)
{
fo(j,1,n-x+1)
tmp[++tot]=calc1(i,j,x);
}
sort(tmp+1,tmp+tot+1);
fo(i,1,n-x+1)
{
fo(j,1,n-x+1)
{
ll v=calc2(i,j,x);
ll pos=*lower_bound(tmp+1,tmp+tot+1,v);
if (pos==v)return 1;
}
}
return 0;
}
int main()
{
bin[0]=1;
fo(i,1,50)bin[i]=bin[i-1]*1321;
scanf("%d",&n);
fo(i,1,n)
{
hash1[i][0]=1;
fo(j,1,n)
{
scanf("%d",&mp1[i][j]);
hash1[i][j]=(1ll*hash1[i][j-1]*1321+mp1[i][j]);
}
}
fo(i,1,n)
{
hash2[i][0]=1;
fo(j,1,n)
{
scanf("%d",&mp2[i][j]);
hash2[i][j]=(1ll*hash2[i][j-1]*1321+mp2[i][j]);
}
}
int l=1,r=n,ans=0;
while (l<=r)
{
int mid=(l+r)>>1;
if (pd(mid))ans=mid,l=mid+1;
else r=mid-1;
}
printf("%d\n",ans);
}