Manacher

作者: WJNominate | 来源:发表于2017-04-22 00:35 被阅读0次

    [hdu 3068|http://acm.hdu.edu.cn/showproblem.php?pid=3068]

    const int MaxN = 1000000 + 7;
    char ms[MaxN * 2];
    int mr[MaxN * 2];
    int manacher( char *s ) {
      int len = strlen( s ), l = 0;
      ms[l++] = '$';
      for( int i = 0; i < len; ++i, l += 2 ) {
        ms[l] = '#', ms[l + 1] = s[i];
      }
      ms[l++] = '#';
    
      int mx = 0, mp = 0, ans = 0;
      for( int i = 0; i < l; ++i ) {
        mr[i] = mx > i ? min( mr[mp * 2 - i], mx - i ) : 1;
        while( ms[i + mr[i]] == ms[i - mr[i]] )  mr[i]++;
        if( i + mr[i] > mx ) {
          mx = i + mr[i], mp = i;
        }
        ans = max( ans, mr[i] - 1 );
      }
    
      return ans;
    }
    
    • Note

      1. 填充首末间隙,并且首部再加一个(使整个串S是回文串时失配)\

      mr[i] = mx > i ? min( mr[mp * 2 - i], mx - i ) : 1;
      while( ms[i + mr[i]] == ms[i - mr[i]] )  mr[i]++;
      if( i + mr[i] > mx ) mx = i + mr[i], mp = i;
    
    1. 类似尺取,S_i 只进一次 => O(n)

    相关文章

      网友评论

          本文标题:Manacher

          本文链接:https://www.haomeiwen.com/subject/ylijzttx.html