POJ-2774 最长公共子串 Hash 二分

该博客介绍了如何使用Hash和二分查找技术解决POJ-2774问题,即找出两个字符串的最长公共子串。通过给出的样例输入和输出,展示了算法的正确性和效率,运行时间为1125ms,内存占用为3836k。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Input
Two strings with lowercase letters on two of the input lines individually. Number of characters in each one will never exceed 100000.
Output
A single line with a single integer number – what is the maximum length of the original text written by the little cat.

Sample Input
yeshowmuchiloveyoumydearmotherreallyicannotbelieveit
yeaphowmuchiloveyoumydearmother
Sample Output
27

Time—1125ms
Memory—3836k
代码:

#include<iostream>
#include<vector>
#include<algorithm>
#include<stdio.h>
#include<string.h>
using namespace std;
typedef unsigned long long ull;
const int N=1e5+7;
char P[N],T[N];
ull hashp[N],hasht[N],pm[N],p=13331;
ull getseg(int l,int r,ull Hash[]){
	return Hash[r]-Hash[l-1]*(pm[r-l+1]);
}
int l1,l2;
vector<ull>q;
bool C(int x){
	q.clear();
	for(int l=1,r=l+x-1;r<=l1;++l,++r)q.push_back(getseg(l,r,hashp));
	sort(q.begin(),q.end());
	for(int l=1,r=l+x-1;r<=l2;++l,++r){
		ull tmp=getseg(l,r,hasht);
	    if(*lower_bound(q.begin(),q.end(),tmp)==tmp)return 1;
	}
	return 0;
}
int main(){
	pm[0]=1;
	for(int i=1;i<N;++i)pm[i]=pm[i-1]*p;
	gets(P+1),gets(T+1);
	l1=strlen(P+1),l2=strlen(T+1);
	for(int i=1;i<=l1;++i)hashp[i]=hashp[i-1]*p+P[i];
	for(int i=1;i<=l2;++i)hasht[i]=hasht[i-1]*p+T[i];
	int l=0,r=min(l1,l2);
	while(l<r){
		int mid=(l+r+1)>>1;
	    if(C(mid))l=mid;
	    else r=mid-1;
	}
	printf("%d\n",l);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值