zoukankan      html  css  js  c++  java
  • 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
    ",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;
    }
    

      

  • 相关阅读:
    网络配置
    数据管理
    仓库
    dockerfile
    docker 概念
    查看日志小技巧
    springboot缓存
    360笔试算法题 AT变换
    删除链表里全部重复元素以及删除链表重复元素只保留一个
    报错类型
  • 原文地址:https://www.cnblogs.com/forever97/p/bzoj4327.html
Copyright © 2011-2022 走看看