刷题总结:最长公共字串(spoj1811)(后缀自动机)

题目:

  就不贴了吧···如题;

题解:

  后缀自动机模版题;没啥好说的····

代码:

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<ctime>
#include<cctype>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
const int N=300;
int pre[N],step[N],son[N][26],tot=1,last=1,root=1;
char s[N];
struct suffix_auto
{
  void extend(int ch)
  {
    int p=last,np=++tot;
    step[tot]=step[last]+1;
    for(;p&&!son[p][ch];p=pre[p])  son[p][ch]=np;
    if(!p)  pre[np]=root;
    else
    {
      int q=son[p][ch];
      if(step[q]!=step[p]+1)
      {
        int nq=++tot;
        step[nq]=step[p]+1;
        memcpy(son[nq],son[q],sizeof(son[q]));
        pre[nq]=pre[q];
        pre[np]=pre[q]=nq;
        for(;son[p][ch]==q;p=pre[p])  son[p][ch]=nq; 
      }
      else
        pre[np]=q;  
    }
    last=np;
  }
  void build()
  {
    scanf("%s",s);
    int len=strlen(s);
    for(int i=0;i<len;i++)
      extend(s[i]-'A');
  }
}automaton;
int main()
{
  automaton.build();
  scanf("%s",s);
  int n=strlen(s);
  int ans=0,len=0,p=0;
  for(int i=0;i<n;i++)
  { 
    int ch=s[i]-'A';
    if(son[p][ch]) p=son[p][ch],len++; 
    else
    { 
      while(p&&!son[p][ch]) p=pre[p];
      if(!p)  len=0,p=root;  
      else
        len=step[p]+1,p=son[p][ch];
    }
    ans=max(ans,len);
  }
  cout<<ans<<endl;
  return 0;
} 

  

原文地址:https://www.cnblogs.com/AseanA/p/6610967.html