zoukankan      html  css  js  c++  java
  • BZOJ 2565 最长双回文串(回文自动机)

    题意

    给一个长度为N的字符串S。对于一个字符串AB,如果A和B都是回文串,那么称AB是一个双回文串。求问S最长双回文子串的长度?
    N <= 100000

    题解

    正反双向构造回文自动机,得到某一个点为结尾和开始的最长回文串长度,记为f[i],g[i];

    答案就是f[i]+g[i+1]的最大值。

     1 #include<iostream>
     2 #include<cstring>
     3 #include<cstdio>
     4 #include<cmath>
     5 #include<algorithm>
     6 using namespace std;
     7 const int N=100500;
     8 int len[N],cnt[N],to[N][30],s[N],fail[N],last,tot,n;
     9 int ans,L,p1[N],p2[N];
    10 char s1[N],s2[N];
    11 void init(){
    12     tot=1;n=0;
    13     len[0]=0;len[1]=-1;
    14     fail[0]=1;s[0]=-1;last=0;
    15     memset(to,0,sizeof(to));
    16 }
    17 void add(int c,int p[]){
    18     s[++n]=c;
    19     int cur,now,tmp;
    20     for(cur=last;s[n-len[cur]-1]!=c;cur=fail[cur]);
    21     if(!to[cur][c]){
    22         tot++;
    23         len[tot]=len[cur]+2;now=tot;
    24         for(tmp=fail[cur];s[n-len[tmp]-1]!=c;tmp=fail[tmp]);
    25         fail[now]=to[tmp][c];
    26         to[cur][c]=now;
    27     }
    28     last=to[cur][c];
    29     cnt[last]++;
    30     p[n]=len[last];
    31 }
    32 int main(){
    33     scanf("%s",s1+1);
    34     int L=strlen(s1+1);
    35     for(int i=1;i<=L;i++)s2[i]=s1[L-i+1];
    36     init();
    37     for(int i=1;i<=L;i++)add(s1[i]-'a',p1);
    38     init();
    39     for(int i=1;i<=L;i++)add(s2[i]-'a',p2);
    40     for(int i=1;i<=L-1;i++){
    41         ans=max(ans,p1[i]+p2[L-i]);
    42     } 
    43     printf("%d",ans);
    44     return 0; 
    45 } 
  • 相关阅读:
    前端 HTML
    python3内置函数
    内置函数的随机验证码
    线程、进程以及协程,上下文管理器
    线程池的定义方法
    python_控制台输出带颜色的文字方法
    while 循环 continue break 用法例子
    JVM 基础知识
    ios 设置状态栏文本颜色为白色
    ios 常用第三方库要加的framework,ARC的设置
  • 原文地址:https://www.cnblogs.com/Xu-daxia/p/9552955.html
Copyright © 2011-2022 走看看