SPOJ 1812 Longest Common Substring II(后缀自动机)

forever97 posted @ 2016年8月24日 00:09 in 字符串-后缀自动机 with tags 后缀自动机 , 604 阅读

 

【题目链接】 http://www.spoj.com/problems/LCS2/

 

【题目大意】

    求n个串的最长公共子串

 

【题解】

    对一个串建立后缀自动机,剩余的串在上面跑,保存匹配每个状态的最小值,取最小值中的最大值即可。由于跑的地方只记录了匹配结尾的状态,所以还需要更新parent树上的状态,既然匹配到了子节点,那么parent树链上的值就都能够取到l,一开始给每个不同状态按照l从小到大分配储存地址,这样,我们就可以从匹配长度最长的开始更新parent树的情况。

 

【代码】

#include <cstdio>
#include <cstring>
#include <algorithm> 
using namespace std;
const int N=500005;
char s[N];
struct sam{
	  int p,q,np,nq,cnt,last,a[N][26],l[N],f[N],mx[N],x[N];
	  sam(){cnt=0;last=++cnt;}
	  void extend(int c){
		    p=last;np=last=++cnt;l[np]=l[p]+1;
		    while(!a[p][c]&&p)a[p][c]=np,p=f[p];
		    if(!p)f[np]=1;
		    else{
			      q=a[p][c];
			      if(l[p]+1==l[q])f[np]=q;
			      else{
				        nq=++cnt;l[nq]=l[p]+1;
				        memcpy(a[nq],a[q],sizeof(a[q]));
				        f[nq]=f[q]; f[np]=f[q]=nq;
				        while(a[p][c]==q)a[p][c]=nq,p=f[p];
			      }
		    }
	  }
	  void build(){
		    scanf("%s",s+1);
		    int len=strlen(s+1);
		    for(int i=1;i<=len;i++)extend(s[i]-'a');
		    for(int i=1;i<=cnt;i++)mx[l[i]]++;
		    for(int i=1;i<=len;i++)mx[i]+=mx[i-1];
		    for(int i=1;i<=cnt;i++)x[mx[l[i]]--]=i;
		    for(int i=1;i<=cnt;i++)mx[i]=l[i];
	  }
	  void doit(){
		    int len=strlen(s+1),tmp=0,p=1;
		    static int arr[N];
		    for(int i=1;i<=len;i++){
			      int c=s[i]-'a';
			      if(a[p][c])p=a[p][c],tmp++;
			      else{
				        while(p&&!a[p][c])p=f[p];
				        if(!p)p=1,tmp=0;
				        else tmp=l[p]+1,p=a[p][c];
			      }arr[p]=max(arr[p],tmp);
		    }for(int i=cnt;i;i--){
		        int t=x[i];
		        mx[t]=min(mx[t],arr[t]);
		        if(arr[t]&&f[t])arr[f[t]]=l[f[t]];
		        arr[t]=0;
		    }
	  }
	  void getans(){
	      int ans=0;
	      for(int i=1;i<=cnt;i++)ans=max(ans,mx[i]);
	      printf("%d\n",ans);
	  }
}sam;
int main(){
    sam.build();
    while(~scanf("%s",s+1))sam.doit();
    sam.getans();
    return 0;
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter