BZOJ 4327 JSOI2012 玄武密码(后缀自动机)

 

【题目链接】 http://www.lydsy.com/JudgeOnline/problem.php?id=4327

 

【题目大意】

  求每个子串在母串中的最长匹配

 

【题解】

  对母串建立后缀自动机,用每个子串在上面匹配即可。

 

【代码】

#include <cstdio>
#include <cstring>
#include <algorithm> 
#include <vector>
using namespace std;
const int N=20000010;
char s[N];
int cal(char c){
    if(c=='S')return 1;
    if(c=='N')return 2;
    if(c=='E')return 3;
    if(c=='W')return 0;
}
struct sam{
	  int p,q,np,nq,cnt,last,a[N][4],l[N],f[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(cal(s[i]));
	  }
	  void solve(){
	      scanf("%s",s+1);
	      int len=strlen(s+1);
	      int p=1,ans=0;
	      for(int i=1;i<=len;i++){
	          int c=cal(s[i]);
	          if(a[p][c])p=a[p][c],ans++;
	          else break; 
	      }printf("%d\n",ans);
	  }
}sam;
int n,m;
int main(){
    scanf("%d%d",&m,&n);
    sam.build();
    for(int i=1;i<=n;i++)sam.solve();
    return 0;
}

  

posted @ 2017-07-17 13:45  forever97  阅读(166)  评论(0编辑  收藏  举报