牛客:矩阵 (二维hash + 二分)

矩阵

在这里插入图片描述

题解:

这题一看题解就豁然了,首先我们处理出字符串矩阵的hash值,然后二分枚举距离,距离的最大范围是 [1,min(n,m)],然后这题数据比较强,好像专门来卡数组取模映射的情况,但是不碍事,我们有 map ,虽然map对于这种 O(n^2)的时间复杂来说有点慢,但是这题显然没有卡,我用取模时,显然重复几率很大。

AC代码:

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e3+5;
#define ull unsigned long long
#define p 1000007
const ull base1=131;
const ull base2=13331;
ull h[501][501],p1[501],p2[501];
char s[501][501];
map<ull,ull>mp;
ull n,m;
bool check(ull x)
{
    mp.clear();
    ull ans;
    for(ull i=x; i<=n; i++)
    {
        for(ull j=x; j<=m; j++)
        {
            ans=h[i][j]-h[i-x][j]*p2[x]-h[i][j-x]*p1[x]+h[i-x][j-x]*p1[x]*p2[x];
            mp[ans]++;
            if(mp[ans]>1)
            {
                return true;
            }
        }
    }
    return false;
}
ull lower(ull l,ull r)
{
    ull ans;
    while(l<=r)
    {
        ull mid=l+r>>1;
        if(check(mid))
        {
            l=mid+1;
            ans=mid;
        }
        else
        {
            r=mid-1;
        }
    }
    return ans;
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cin>>n>>m;
    for(ull i=1; i<=n; i++)
        cin>>s[i]+1;
    p1[0]=p2[0]=1;
    for(ull i=1; i<=501; i++)
        p1[i]=p1[i-1]*base1,p2[i]=p2[i-1]*base2;
    for(ull i=1; i<=n; i++)
        for(ull j=1; j<=m; j++)
            h[i][j]=h[i][j-1]*base1+s[i][j]-'a';
    for(ull i=1; i<=n; i++)
        for(ull j=1; j<=m; j++)
            h[i][j]+=h[i-1][j]*base2;
           ull c=min(n,m);
     ull ans=lower(1,c);
     cout<<ans<<endl;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值