SP1811-Longest Common Substring【SAM】
生活随笔
收集整理的這篇文章主要介紹了
SP1811-Longest Common Substring【SAM】
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
正題
題目鏈接:https://www.luogu.com.cn/problem/SP1811
題目大意
求兩個串的最長公共子串。
解題思路
對與第一個串首先構建一個SAMSAMSAM,然后考慮讓第二個串在上面匹配。
對于枚舉的每個位置要在SAMSAMSAM上找一個節點使得它的后綴是枚舉到的位置的后綴。所以對于當前節點如果有新加入的字符串的邊就走過去,如果沒有我們就可以在parentparentparent樹上往前跳,因為跳到的節點代表的后綴是滿足且僅滿足這些位置的后綴是加入這個字符之前的后綴,跳了之后取那個節點的lenlenlen就好了。
時間復雜度O(n)O(n)O(n)
codecodecode
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int N=5e5+10; int n,las,tot,len[N],fa[N]; char s[N];int ch[N][26],ans; void add(int c){int p=las;int np=las=++tot;len[np]=len[p]+1;for(;p&&!ch[p][c];p=fa[p])ch[p][c]=np;if(!p)fa[np]=1;else{int q=ch[p][c];if(len[p]+1==len[q])fa[np]=q;else{int nq=++tot;len[nq]=len[p]+1;memcpy(ch[nq],ch[q],sizeof(ch[q]));fa[nq]=fa[q];fa[q]=fa[np]=nq;for(;p&&ch[p][c]==q;p=fa[p])ch[p][c]=nq;}}return; } int main() {las=tot=1;scanf("%s",s+1);n=strlen(s+1);for(int i=1;i<=n;i++)add(s[i]-'a');memset(s,0,sizeof(s));scanf("%s",s+1);n=strlen(s+1);int now=1,L=0;for(int i=1;i<=n;i++){int c=s[i]-'a';if(ch[now][c])now=ch[now][c],++L;else{for(;now&&!ch[now][c];now=fa[now]);if(now)L=len[now]+1,now=ch[now][c];else L=0,now=1;}ans=max(ans,L);}printf("%d",ans); }總結
以上是生活随笔為你收集整理的SP1811-Longest Common Substring【SAM】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CF1419E-Decryption【数
- 下一篇: 用牛车拉卫星,印度这样实现廉价探月计划