[SPOJ1811]LCS - Longest Common Substring(后缀自动机)
来源:互联网 发布:知乎怎么看文章阅读量 编辑:程序博客网 时间:2024/06/11 23:09
题目描述
传送门
题意:给出两个串,求最长公共子串。
题解
这明明就是一道sa的题嘛,可是为了练习sam用sam来写
后缀自动机第一题
首先对第一个串建立sam
让第二个串在sam上暴力匹配,匹配不到就蹦到它的pre指针
维护一个能匹配上的最长长度
值得注意的是,因为每一个点pre指针指向的点所确定的串一定是当前点所确定的串的一个后缀,所以如果一个点匹配上了,一旦需要顺着pre指针向上蹦,那么这些点当前能匹配上的长度应该是step
之前一直让我非常困惑的是这个问题:如果一个点匹配上了,那么其pre指针指向的点也可以匹配,但是为什么能匹配的长度就是step,当前点匹配的长度没有可能比step小么
实际上这个问题非常简单!利用自动机的性质,当前点能匹配上的长度一定在其合法的区间里,而min(a)=max(parent(a))+1,所以是一定不会小
由于只需要取一下max,所以不用更新不到的就不用更新了
代码
#include<iostream>#include<cstring>#include<cstdio>using namespace std;#define N 500005char s[N];int n,p,np,q,nq,root,last,sz,ans;int ch[N][30],pre[N],step[N];void extend(){ for (int i=0;i<n;++i) { int x=s[i]-'a'; p=last;np=++sz;last=np; step[np]=step[p]+1; while (p&&!ch[p][x]) { ch[p][x]=np; p=pre[p]; } if (!p) pre[np]=root; else { int q=ch[p][x]; if (step[q]==step[p]+1) pre[np]=q; else { nq=++sz; step[nq]=step[p]+1; memcpy(ch[nq],ch[q],sizeof(ch[q])); pre[nq]=pre[q]; while (ch[p][x]==q) { ch[p][x]=nq; p=pre[p]; } pre[np]=pre[q]=nq; } } }}void sam(){ int len=0; for (int i=0;i<n;++i) { int x=s[i]-'a'; if (ch[p][x]) p=ch[p][x],++len; else { while (p&&!ch[p][x]) p=pre[p]; if (!p) p=1,len=0; else { len=step[p]+1; p=ch[p][x]; } } ans=max(ans,len); }}int main(){ gets(s);n=strlen(s); root=last=++sz; extend(); gets(s);n=strlen(s); sam(); printf("%d\n",ans);}
0 0
- spoj1811 Longest Common Substring(LCS),后缀自动机
- [SPOJ1811]LCS - Longest Common Substring(后缀自动机)
- SPOJ1811 Longest Common Substring后缀自动机
- [SPOJ1811]Longest Common Substring-后缀自动机
- [SPOJ1811]LCS - Longest Common Substring
- SPOJ LCS Longest Common Substring 后缀自动机
- [SPOJ LCS]Longest Common Substring && 后缀自动机
- 【后缀自动机】[SPOJ LCS]Longest Common Substring
- spoj1811 Longest Common Substring(LCS)最长公共子串
- spoj 1811 LCS - Longest Common Substring (后缀自动机)
- 【后缀自动机】SPOJ(LCS)[Longest Common Substring]题解
- spoj1811 Longest Common Substring
- SPOJ1812:Longest Common Substring(后缀自动机)
- SPOJ 题目1811 LCS - Longest Common Substring(后缀自动机求最长公共子串)
- 【spoj1811】Longest Common Substring【SAM】
- LCS(longest common subsequence)与LCS(longest common substring)以及后缀数组
- 后缀数组 spoj LCS - Longest Common Substring
- SPOJ 1811. Longest Common Substring (LCS,两个字符串的最长公共子串, 后缀自动机SAM)
- 2017年值得一看的设计趋势(四)
- 无缝连接封装
- hadoop2.6.1源码编译
- cs231n:assignment2——python文件:fc_net.py
- LDA(Linear discriminant analysis)线性判别式理解
- [SPOJ1811]LCS - Longest Common Substring(后缀自动机)
- Android开发——openFileOutput和openFileIntput用法
- 登陆框封装
- 枚举在接口的应用
- Java对象在Java虚拟机中的内存布局
- 微信开发 - 微擎管理微信公众号
- 比较String对象时需注意
- GIS之旅——研究生总结
- 最大子矩阵和