SPOJ1811 LCS - Longest Common Substring

传送门[洛谷]

SAM板子题?(可惜我还是不会

大概就是能匹配就一直往下匹配

不能匹配就跳parent 调到能匹配为止 跳到根了就重新开始

最开始太蠢了非要写递归版 写着写着发现不知道我要写啥了T^T 果断换循环。。

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#define inf 20021225
#define ll long long
#define mxn 250010
using namespace std;

struct node{int ch[26],fa,len;}t[mxn*4];
int poi,rt,lt,ans,n;char ch[mxn];
int id(char ch){return ch-'a';}
void insert(int c)
{
    int p=lt,np=lt=++poi; t[np].len=t[p].len+1;
    for(;p&&!t[p].ch[c];p=t[p].fa)	t[p].ch[c]=np;
    if(!p){t[np].fa=rt;return;}
    int q=t[p].ch[c];
    if(t[q].len==t[p].len+1){t[np].fa=q;return;}
    int nq=++poi;t[nq].len=t[p].len+1;
    memcpy(t[nq].ch,t[q].ch,sizeof(t[q].ch));
    t[nq].fa=t[q].fa; t[q].fa=t[np].fa=nq;
    for(;p&&t[p].ch[c]==q;p=t[p].fa)	t[p].ch[c]=nq;
}
void find()
{
    int pos=rt,cur=0;
    for(int i=1;i<=n;i++)
    {
        int tmp=id(ch[i]);
        ans=max(ans,cur);
        if(t[pos].ch[tmp])	cur++,pos=t[pos].ch[tmp];
        else
        {
            for(;pos&&!t[pos].ch[tmp];pos=t[pos].fa);
            if(pos)	cur=t[pos].len+1,pos=t[pos].ch[tmp];
            else	cur=0,pos=rt;
        }
    }
    ans=max(ans,cur);
}
int main()
{
    scanf("%s",ch+1);n=strlen(ch+1);
    rt=lt=++poi;
    for(int i=1;i<=n;i++)	insert(id(ch[i]));
    scanf("%s",ch+1);n=strlen(ch+1);
    find();
    printf("%d\n",ans);
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值