博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SPOJ1811 LCS - Longest Common Substring(后缀自动机)
阅读量:6889 次
发布时间:2019-06-27

本文共 2133 字,大约阅读时间需要 7 分钟。

A string is finite sequence of characters over a non-empty finite set Σ.

In this problem, Σ is the set of lowercase letters.

Substring, also called factor, is a consecutive sequence of characters occurrences at least once in a string.

Now your task is simple, for two given strings, find the length of the longest common substring of them.

Here common substring means a substring of two or more strings.

Input

The input contains exactly two lines, each line consists of no more than 250000 lowercase letters, representing a string.

Output

The length of the longest common substring. If such string doesn't exist, print "0" instead.

Example

Input:alsdfkjfjkdsalfdjskalajfkdslaOutput:3

Notice: new testcases added

 

为什么都说这是后缀自动机的裸题啊。难道就我看不出来么qwq、、

正解其实比较好想,先把第一个串扔到SAM里面

对于第二个串依次枚举,如果能匹配就匹配,否则就沿着parent边走(怎么这么像AC自动机??),顺便记录一下最长长度

 

 

#include
#include
#include
using namespace std;const int MAXN = 2 * 300000 + 1;char s1[MAXN], s2[MAXN];int N1, N2, tot = 1, root = 1, last = 1, len[MAXN], ch[MAXN][27], fa[MAXN];void insert(int x) { int now = ++tot, pre = last; last = now; len[now] = len[pre] + 1; for(; pre && !ch[pre][x]; pre = fa[pre]) ch[pre][x] = now; if(!pre) fa[now] = root; else { int q = ch[pre][x]; if(len[q] == len[pre] + 1) fa[now] = q; else { int nows = ++tot; memcpy(ch[nows], ch[q], sizeof(ch[q])); len[nows] = len[pre] + 1; fa[nows] = fa[q]; fa[now] = fa[q] = nows; for(; pre && ch[pre][x] == q; pre = fa[pre]) ch[pre][x] = nows; } } }int main() {#ifdef WIN32 freopen("a.in", "r", stdin);#endif scanf("%s %s", s1 + 1, s2 + 1); N1 = strlen(s1 + 1); N2 = strlen(s2 + 1); for(int i = 1; i <= N1; i++) insert(s1[i] - 'a'); int ans = 0, nowlen = 0, cur = root; for(int i = 1; i <= N2; i++, ans = max(ans, nowlen)) { int p = s2[i] - 'a'; if(ch[cur][p]) {nowlen++, cur = ch[cur][p]; continue;} for(; cur && !ch[cur][p]; cur = fa[cur]); nowlen = len[cur] + 1, cur = ch[cur][p]; } printf("%d\n", ans); return 0;}

转载地址:http://eeqbl.baihongyu.com/

你可能感兴趣的文章
vue开发学习中遇到的问题以及解决方法
查看>>
[xpath] text()和string()区别
查看>>
南阳366--D的小L(Dfs)
查看>>
maven项目SpringBoot框架
查看>>
fail-fast 机制 思考
查看>>
.NET细节知识总结,不断更新
查看>>
SGU112
查看>>
ajax学习总结
查看>>
ruby 访问权限
查看>>
Codeforces Round #327 590B Chip 'n Dale Rescue Rangers(等效转换,二分)
查看>>
Angular 学习笔记 (Material Datepicker)
查看>>
Docker 常用命令
查看>>
Roman Numeral Converter
查看>>
HDFS 异常处理与恢复
查看>>
asp.net core输出中文乱码的问题
查看>>
该对象尚未初始化。请确保在所有其他初始化代码后面的应用程序启动代码中调用 HttpConfiguration.EnsureInitialized()。...
查看>>
转:CentOS7 下 Redis4 安装与配置教程(Redis开机启动)
查看>>
ASP.NET中Repeater控件行颜色交替显示
查看>>
【总结整理】javascript进阶学习(慕课网)
查看>>
汕头市队赛 SRM10 T3 数学上来先打表
查看>>