【SPOJ】Longest Common Substring

求两个字符串的最长公共子串

对一个串建好后缀自动机然后暴力跑一下 废话

讲一下怎么跑吧

从第一个字符开始遍历,遍历不到了再沿着\(parents\)走看能否找到出路,走到某个点时,统计一下走过了多少点然后更新答案

来说说这样做的正确性:

遍历是肯定的, SAM 从根节点出发的任意路径都表示一个子串

沿着\(parents\)边往后走,保证贪心情况下维护最长公共子串寻找出路

注意这里是统计走过了多少点更新答案,不能直接通过\(len\)更新答案

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<set>
#include<map>
#include<vector>
#include<queue>
using namespace std;
typedef long long LL;
const LL maxn=600000;
LL nod,last,n,T;
LL len[maxn],fail[maxn],son[maxn][26];
char s[maxn];
inline void Insert(LL c){
LL np=++nod,p=last;
len[np]=len[p]+1;
last=np;
while(p&&!son[p][c]){
son[p][c]=np,
p=fail[p];
}
if(!p)
fail[np]=1;
else{
LL q=son[p][c];
if(len[q]==len[p]+1)
fail[np]=q;
else{
LL nq=++nod;
len[nq]=len[p]+1;
fail[nq]=fail[q];
memcpy(son[nq],son[q],sizeof(son[q]));
fail[np]=fail[q]=nq;
while(p&&son[p][c]==q){
son[p][c]=nq,
p=fail[p];
}
}
}
}
int main(){
nod=last=1;
scanf(" %s",s);
LL Len=strlen(s);
for(LL i=0;i<Len;++i)
Insert(s[i]-'a');
scanf(" %s",s);
LL ans=0,now=1,cnt=0;
Len=strlen(s);
for(LL i=0;i<Len;++i){
LL c=s[i]-'a';
if(son[now][c])
++cnt,
now=son[now][c];
else{
while(now&&!son[now][c])
now=fail[now];
if(!now)
cnt=0,
now=1;
else
cnt=len[now]+1,
now=son[now][c];
}
ans=max(ans,cnt);
}
printf("%lld\n",ans);
return 0;
}/*
fjewiofejhiofjmwopejeugfzjkjnfoakweldnfmoierhguiewkjfkowejrfoiwejsfd
jwierhdwuiek,dedjfkz[pjeowrfhuqigrfwerljfiuekdfkcdfheosf
*/

最新文章

  1. Entity Framework 6 Recipes 2nd Edition(10-6)译 -&gt; TPT继承模型中使用存储过程
  2. iOS证书问题
  3. ActiveReports 报表应用教程 (7)---交叉报表及数据透视图实现方案
  4. MVP Community Camp 社区大课堂
  5. scala中的=&gt;符号的含义
  6. css3随笔
  7. iOS系统弃用方法更新方法
  8. python requests get/post
  9. null == undefined ?
  10. 【实验手册】使用Visual Studio Code 开发.NET Core应用程序
  11. tomcat实现热部署的配置
  12. Unity2D Sprite灰白图(Unity3D开发之十一)
  13. maven 常用备忘录
  14. Python建立时间事件引擎原理剖析
  15. HTML自学笔记
  16. iOS 使用xib定义一个View,修改frame无效问题解决
  17. 初始easyUI
  18. 泡泡一分钟:A Multi-Position Joint Particle Filtering Method for Vehicle Localization in Urban Area
  19. [CodeForces - 447E] E - DZY Loves Fibonacci Numbers
  20. 从零开始的四轴飞行器-开篇flag

热门文章

  1. .NET Standards
  2. Vue的学习笔记
  3. iOS CALayer总结——图层几何
  4. Django之过滤器
  5. Python requests.post嵌套多层json参数调用接口
  6. 使用框架时,在web.xml中配置servlet时,拦截请求/和/*的区别。
  7. ubuntu 修改环境变量(PATH)
  8. Java stackoverflowerror异常与outofmemoryerror异常区别
  9. .NET Core WebAPI IIS 部署问题
  10. 前端学习笔记--CSS入门