codevs 3160(后缀自动机复习)

题目描述 Description

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

输入描述 Input Description

读入两个字符串

输出描述 Output Description

输出最长公共子串的长度

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

27

数据范围及提示 Data Size & Hint

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


解题思路:后缀自动机


#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
char a[100001],b[100001];
int last,cnt,ans,len1,len2,now;
int mx[100010],fa[100010];
int ch[100010][27];


inline int read()
 {
  char y; int x=0,f=1; y=getchar();
  while (y<'0' || y>'9') {if (y=='-') f=-1; y=getchar();}
while (y>='0' && y<='9') {x=x*10+int(y)-48; y=getchar();}
return x*f;
 }


void build(int s)
 {
  int p=last; int np=last=++cnt; mx[np]=mx[p]+1;
  while (p!=0 && !ch[p][s]) ch[p][s]=np,p=fa[p];
  if (p==0) fa[np]=1;else
  {
  int q=ch[p][s];
  if (mx[q]==mx[p]+1)
  {
  fa[np]=q;
}else
 {
  int nq=++cnt; mx[nq]=mx[p]+1;
  memcpy(ch[nq],ch[q],sizeof(ch[nq]));
  fa[nq]=fa[q];
  fa[q]=fa[np]=nq;
  while (p!=0 && ch[p][s]==q) ch[p][s]=nq,p=fa[p];
 }
 }
 }


int main()
{
scanf("%s",a); scanf("%s",b);
len1=strlen(a); len2=strlen(b);
cnt=1; last=1;
for (int i=1;i<=len1;++i)
{
build(a[i-1]-'a');
}
now=1;
int ans=-1; int tmp=0; 
for (int i=1;i<=len2;++i)
{
  int s=b[i-1]-'a';
  if (ch[now][s]) ++tmp,now=ch[now][s];else
   {
    while (!ch[now][s] && now!=0) now=fa[now];
    if (now==0) now=1,tmp=0;else
    tmp=mx[now]+1,now=ch[now][s];
}
ans=max(ans,tmp);
}
printf("%d",ans);
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值