最长公共子串,二分+哈希,求帮忙查错
#include<stdio.h>#include<stdlib.h>
#include<string.h>
int hash1[3938]={0},hash2[4128]={0},hash3[2084]={0},hash4[3030]={0};
long long i,j,n,len,l1,l2,k,flag=0;
char s1[100001],s2[100001];
void h(int a,int b) //将对应的子串处理成27进制数,存入4个哈希数组
{
long long i,y=0,z=3937*4127*2083*3029;
for (i=a;i<=b;i++)
{
y*=27;
y+=s1[i]-'a'+1;
y%=z;
}
hash1[y%3937]=1;
hash2[y%4127]=1;
hash3[y%2083]=1;
hash4[y%3029]=1;
}
long long num(int a,int b) //算出匹配串对应的27进制数
{
long long i,y=0,z=3937*4127*2083*3029;
for (i=a;i<=b;i++)
{
y*=27;
y+=s2[i]-'a'+1;
y%=z;
}
return y;
}
void resehash() //重设hash数组
{
for (i=0;i<=2083;i++)
{
hash1[i]=0;
hash2[i]=0;
hash3[i]=0;
hash4[i]=0;
}
for (i=2084;i<=3029;i++)
{
hash1[i]=0;
hash2[i]=0;
hash4[i]=0;
}
for (i=3030;i<=3937;i++)
{
hash1[i]=0;
hash2[i]=0;
}
for (i=3938;i<=4127;i++)
hash2[i]=0;
}
void guess(int start,int end) //二分查找
{
long long i,j,w,x,y,z=0;
if (flag>0) return;
if (start==end) {flag=1; printf("%d\n",start);return; }
x=(start+end)/2; w=(start+end)%2; x+=w; //x为阶段中间值
for (i=0;i<=l1-x;i++)
h(i,i+x-1); //哈希
for (i=0;i<=l2-x;i++) //在s2中匹配
{
y=num(i,i+x-1); //算出匹配串对应的27进制数
if (hash1[y%3937]>0&&hash2[y%4127]>0&&hash3[y%2083]>0&&hash4[y%3029]>0) //4个哈希数组全部符合
{
z=1; break; //可以达到
}
}
if (z==1) { resehash(); guess(x,end); return; } //往大的方向找
guess(start,x-1); //否则往小的方向找
return;
}
int main()
{
scanf("%s",s1);
scanf("%s",s2);
l1=strlen(s1); l2=strlen(s2);
if (l1<l2) k=l1;
else k=l2;
guess(0,k);
system("pause");
}
手动生成的小数据都过了,大数据WA的WA,TLE的TLE。
附加两个数据:
输入1:
mbmkdvlxagiduexvgrkjnmluxyauzlblprxwojnkyawndlgntrusgxxghduigmknrseoiencjxqswgcpaahrbyszeckvqsruzxxkmsyugxoesnzuswjgrgmjmxltgstrztewlhxuegcmgymqbwdbjrpogzdpudbelixqjlycejuazmjizvfyanhbeizayyndxeujjfunhvilpudqybbaxknipdfujlwqdmzbcknxjbfdzmxgxkxabpdrcbqjgjwxotcmtvdflpjehhjlcptyykrzdyqjbyxnkuptdgapvhylgwhvrlmiflpgovjcgzzlbwkxndudltcqkfpmoqasmttmuxvyytcujloqubbuojptptrvadelpgoctoaxzagurdnkrlbopnxajvuwjpfyvbztwbiwuvabidqcvwbxqjaylvlfshtdntejotzwbeyqdkacckvimdrqnwqhvfcgakkksgqscgfjdkxkxbovptmuhhmznbubvbravztspakuigjqnztciwdayevhjwjhslxvwnytwqxycjphlasiprmnirlnghsqvxiemizlexoxyvfmcmhabfvvaxcxxteqofmesakcyekmsuihbxkyvaqyppexzwruktftakfdvzuthbgifvluiudxmqkxpvegwijnndoobluyyvangybetmsqaakjfxvzvzbgkrtn
mbmkdvlxagiduexvgrkjnmluxyauzlblprxwojnkyawndlgntrusgxxghduigmknrseoiencjxqswgcpaahrbyszeckvqsruzxxkmsyugxoesnzuswjgrgmjmxltgstrztewlhxuegcmgymqbwdbjrpogzdpudbelixqjlycejuazmjizvfyanhbeizayyndxeujjfunhvilpudqybbaxknipdfujlwqdmzbcknxjbfdzmxgxkxabpdrcbqjgjwxotcmtvdflpjehhjlcptyykrzdyqjbyxnkuptdgapvhylgwhvrlmiflpgovjcgzzlbwkxndudltcqkfpmoqasmttmuxvyytcujloqubbuojptptrvadelpgoctoaxzagurdnkrlbopnxajvuwjpfyvbztwbiwuvajidqcvwbxqjaylvlfshtdntejotzwbeyqdkacckvimdrqnwqhvfcgakkksgqscgfjdkxkxbovptmuhhmznbubvbravztspakuigjqnztciwdayevhjwjhslxvwnytwqxycjphlasiprmnirlnghsqvxi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