SPOJ1811 LCS - Longest Common Substring(后缀…
2018-06-27 09:43:01来源:博客园 阅读 ()
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: alsdfkjfjkdsal fdjskalajfkdsla Output: 3
Notice: new testcases added
为什么都说这是后缀自动机的裸题啊。难道就我看不出来么qwq、、
正解其实比较好想,先把第一个串扔到SAM里面
对于第二个串依次枚举,如果能匹配就匹配,否则就沿着parent边走(怎么这么像AC自动机??),顺便记录一下最长长度
#include<cstdio> #include<cstring> #include<algorithm> 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; }
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
上一篇:树上莫队算法
- Longest Ordered Subsequence 2020-02-09
- 最长上升子序列(LIS: Longest Increasing Subsequence) 2019-09-08
- The Xor-longest Path(trie树) 2019-08-16
- Longest Substring Without Repeating Characters 2019-08-16
- 51Nod-1006 最长公共子序列Lcs 2018-10-03
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash