POJ 2774 Long Long Message (二分 + Hash 求最长公共子串)题解

时间:2024-08-27 17:04:44

题意:求最长公共子串

思路:把两个串Hash,然后我们把短的作为LCS的最大可能值,然后二分长度,每次判断这样二分可不可以。判断时,先拿出第一个母串所有len长的子串,排序,然后枚举第二个母串len长度字串,二分查找在第一个母串的子串中存不存在。

代码:

#include<cmath>
#include<stack>
#include<queue>
#include<cstdio>
#include<vector>
#include<cstring>
#include <iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int maxn = + ;
const ull seed = ;
const int INF = 0x3f3f3f3f;
const int MOD = ;
ull hs[maxn], hp[maxn], fac[maxn], q[maxn];
int len1, len2;
char s[maxn], p[maxn];
ull get_hash(ull *h, int l, int r){
return h[r] - h[l - ] * fac[r - l + ];
}
bool check(int len){
int cnt = ;
for(int i = ; i + len - <= len1; i++){
q[cnt++] = get_hash(hs, i, i + len - );
}
sort(q, q + cnt);
for(int i = ; i + len - <= len2; i++){
ull aim = get_hash(hp, i, i + len - );
if(binary_search(q, q + cnt, aim)) return true;
}
return false;
}
int main(){
fac[] = ;
for(int i = ; i < maxn; i++)
fac[i] = fac[i - ] * seed;
while(~scanf("%s%s", s + , p + )){
len1 = strlen(s + );
len2 = strlen(p + );
hs[] = hp[] = ;
for(int i = ; i <= len1; i++)
hs[i] = hs[i - ] * seed + (s[i] - 'a');
for(int i = ; i <= len2; i++)
hp[i] = hp[i - ] * seed + (p[i] - 'a');
int l = , r = min(len1, len2);
int ans = ;
while(l <= r){
int m = (l + r) >> ;
if(check(m)){
l = m + ;
ans = m;
}
else{
r = m - ;
}
}
printf("%d\n", ans);
}
return ;
}