codevs 3160 最长公共子串

本文介绍了一种使用后缀自动机(SAM)求解两个字符串最长公共子串的方法。通过构建SAM并遍历第二个字符串来高效寻找最长公共子串。适用于字符串长度不超过10万的应用场景。

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

题目描述 Description

给出两个由小写字母组成的字符串,求它们的最长公共子串的长度。

输入描述 Input Description

读入两个字符串

输出描述 Output Description

输出最长公共子串的长度

样例输入 Sample Input
yeshowmuchiloveyoumydearmotherreallyicannotbelieveit
yeaphowmuchiloveyoumydearmother
样例输出 Sample Output

27

数据范围及提示 Data Size & Hint

单个字符串的长度不超过100000





【分析】

类似失配指针...?

还是需要用到SAM的神奇性质:i和parent[i]的LCS是s[1]~s[parent[i]]

还有:从根出发的任意一条路径都是原串的一个子串

先把A串建立SAM,然后B串在上面跑呀跑,跑不了就跳pre。




【代码】

//codevs 3160 最长公共子串 
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#define ll long long
#define M(a) memset(a,0,sizeof a)
#define fo(i,j,k) for(i=j;i<=k;i++)
using namespace std;
const int mxn=100005;
char s[mxn];
int n,m,len,p,q,np,nq,root,tot,ans,cnt;
int son[mxn<<1][30],pre[mxn<<1],step[mxn<<1];
inline void sam()
{
	int i,j;
	scanf("%s",s+1);
	len=strlen(s+1);
	np=root=tot=1;
	fo(i,1,len)
	{
		int c=s[i]-'a'+1;
		p=np;
		step[np=(++tot)]=step[p]+1;
		while(p && !son[p][c])
		  son[p][c]=np,p=pre[p];
		if(!p)
		{
			pre[np]=root;
			continue;
		}
		q=son[p][c];
		if(step[q]==step[p]+1)
		  pre[np]=q;
		else
		{
			step[nq=(++tot)]=step[p]+1;
			fo(j,1,26) son[nq][j]=son[q][j];
			pre[nq]=pre[q];
			pre[q]=pre[np]=nq;
			while(p && son[p][c]==q)
			  son[p][c]=nq,p=pre[p];
		}
	}
}
inline void find()
{
	scanf("%s",s+1);
	len=strlen(s+1);
	int now=root,i,j;
	fo(i,1,len)
	{
		int c=s[i]-'a'+1;
		if(son[now][c])
		  now=son[now][c],cnt++;
		else
		{
			while(now && !son[now][c])
			  now=pre[now];
			if(!now) now=root,cnt=0;
			else cnt=step[now]+1,now=son[now][c];
		}
		ans=max(ans,cnt);
	}
}
int main()
{
	int i,j;
	sam();
	find();
	printf("%d\n",ans);
	return 0;
}
//shh
//phh


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值