Lcs-longest Common Substring
No Tags
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 was simple, for the given strings, find the length of the longest common substring of them.
Here common substring means a substring of the or more strings.
Input
The input contains exactly the 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
The problem is to ask for the longest common string, so I applied Sam directly.
1#include <iostream>2#include <cstdio>3#include <cstring>4 using namespacestd;5 Const intmaxn=1000010;6 structsam{7 intfa[maxn],ch[maxn][ -],len[maxn],cnt,last;8 voidInit ()9 {TenLast=cnt=1; One } A voidInsert (intc) - { - intp=last,np=last=++CNT; thelen[np]=len[p]+1; - while(!ch[p][c]&&p) -ch[p][c]=np,p=Fa[p]; - if(!p) fa[np]=1; + Else{ - intq=Ch[p][c]; + if(len[q]==len[p]+1) Afa[np]=Q; at Else{ - intnq=++cnt;len[nq]=len[p]+1; -memcpy (Ch[nq],ch[q],sizeof(Ch[p])); -fa[nq]=fa[q];fa[q]=fa[np]=NQ; - while(ch[p][c]==q) -ch[p][c]=nq,p=Fa[p]; in } - } to } + }sam; - CharSTR1[MAXN],STR2[MAXN]; the intMain () * { $ intlen1=0, len2=0, ans=0;Panax Notoginsengscanf"%s%s", STR1,STR2); - Sam. Init (); the while(Str1[len1]) +Sam. Insert (str1[len1++]-'`'); A intNode=1, tmp=0; the for(; str2[len2];len2++){ + intc=str2[len2]-'`'; - if(Sam.ch[node][c]) $node=sam.ch[node][c],tmp++; $ Else{ - while(node&&!Sam.ch[node][c]) -Node=Sam.fa[node]; the if(node==0) -Node=1, tmp=0;Wuyi Else thetmp=sam.len[node]+1, node=Sam.ch[node][c]; - } Wuans=Max (ans,tmp); - } Aboutprintf"%d\n", ans); $ return 0; -}
Suffix Automaton (SAM): Spoj lcs-longest Common Substring