http://www.pipioj.online/problem.php?id=1476
Idea: Through string hashing, it can be in O (n) O (n)Calculate the length within O ( n ) complexity to belen lenl e n alls 1 s_1s1The hash value of the substring of is stored in a hash table, then it can be in O (n) O(n)O ( n ) Judges 1, s 2 s_1, s_2within complexitys1、s2Whether there is a common substring. Length of bipartite common substring, complexity O (nlgn) O(nlgn)O ( n l g n )。
#include<bits/stdc++.h>
#define INF 0x3f3f3f3f
using namespace std;
using ull=unsigned long long;
const int maxn=1e5+5;
const int bs=127;
int n;
char s1[maxn],s2[maxn];
ull s1hash[maxn],s2hash[maxn],base[maxn];
inline bool check(int len)
{
unordered_map<ull,bool> hs;
ull tmp=s1hash[len];
for(int i=len;i<n;i++)
{
hs[tmp]=1;
tmp=(tmp-s1[i-len]*base[len-1])*bs+s1[i];
}
hs[tmp]=1;
tmp=s2hash[len];
for(int i=len;i<n;i++)
{
if(hs.count(tmp))
return 1;
tmp=(tmp-s2[i-len]*base[len-1])*bs+s2[i];
}
return hs.count(tmp);
}
int main()
{
base[0]=1;
scanf("%d%s%s",&n,s1,s2);
for(int i=1;i<=n;i++)
s1hash[i]=s1hash[i-1]*bs+s1[i-1];
for(int i=1;i<=n;i++)
{
s2hash[i]=s2hash[i-1]*bs+s2[i-1];
base[i]=base[i-1]*bs;
}
int l=0,r=n,mid;
while(l<=r)
{
mid=(l+r)>>1;
if(check(mid))
l=mid+1;
else
r=mid-1;
}
printf("%d\n",r);
return 0;
}