zoukankan      html  css  js  c++  java
  • hdu 3068 最长回文子串(马拉车算法)

    求最长回文子串的长度,字符串非常长,我们采用复杂度为线性的manacher算法。

    马拉车算法:

    http://www.cnblogs.com/biyeymyhjob/archive/2012/10/04/2711527.html

     1 #include <iostream>
     2 #include <cstring>
     3 #include <cstdio>
     4 using namespace std;
     5 
     6 const int N = 110010;
     7 char str[N];
     8 char tmp[N << 1];
     9 int len[N << 1];
    10 
    11 int convert( char * st, char * dst )
    12 {
    13     int l = strlen(st);
    14     dst[0] = '@';
    15     for ( int i = 1; i <= 2 * l; i += 2 )
    16     {
    17         dst[i] = '#';
    18         dst[i + 1] = st[i / 2];
    19     }
    20     dst[2 * l + 1] = '#';
    21     dst[2 * l + 2] = 0;
    22     return 2 * l + 1;
    23 }
    24 
    25 int manacher( char * st, char * dst )
    26 {
    27     int l = convert( st, dst );
    28     int mx = 0, ans = 0, po = 0;
    29     for ( int i = 1; i <= l; i++ )
    30     {
    31         if ( mx > i )
    32         {
    33             len[i] = min( mx - i, len[2 * po - i] );
    34         }
    35         else
    36         {
    37             len[i] = 1;
    38         }
    39         while ( dst[i - len[i]] == dst[i + len[i]] )
    40         {
    41             len[i]++;
    42         }
    43         if ( len[i] + i > mx )
    44         {
    45             mx = len[i] + i;
    46             po = i;
    47         }
    48         ans = max( ans, len[i] );
    49     }
    50     return ans - 1;
    51 }
    52 
    53 int main ()
    54 {
    55     while ( scanf("%s", str) != EOF )
    56     {
    57         int o = manacher( str, tmp );
    58         printf("%d
    ", o);
    59     }
    60     return 0;
    61 }
  • 相关阅读:
    Investment
    The Fewest Coins
    Bone Collector II
    Cow Exhibition
    饭卡
    A + B Problem II
    F
    敌兵布阵
    单例模式
    面向对象
  • 原文地址:https://www.cnblogs.com/huoxiayu/p/4675364.html
Copyright © 2011-2022 走看看