zoukankan      html  css  js  c++  java
  • ACM题目————最长回文串

    Description

    给出一个只由小写英文字符a,b,c...y,z组成的字符串S,求S中最长回文串的长度.
    回文就是正反读都是一样的字符串,如aba, abba等
     

    Input

    输入有多组case,不超过120组,每组输入为一行小写英文字符a,b,c...y,z组成的字符串S
    两组case之间由空行隔开(该空行不用处理)
    字符串长度len <= 110000
     

    Output

    每一行一个整数x,对应一组case,表示该组case的字符串中所包含的最长回文长度.
     

    Sample Input

    aaaa abab
     

    Sample Output

    4 3

    用manacher算法求最长回文串长度。

    #include <iostream>
    #include <algorithm>
    #include <cstring>
    #include <cstdio>
    #include <cctype>
    #include <cstdlib>
    #include <stack>
    #include <cmath>
    #include <string>
    #include <queue>
    #define INF 10000001
    
    using namespace std;
    const int maxn = 110005*2;
    char str[maxn];
    int p[maxn];
    
    void manacher(char *s, int len){
        p[0] = 1 ;
        int Max = 0, d= 0 ;
        for(int i=1; i<len; i++){
            p[i] = Max > i ? min(p[d*2-i],Max-i):1 ;
            while( s[i+p[i]] == s[i-p[i]]) p[i] ++ ;
            if( i + p[i] > d + p[d] ){
                d = i ;
                Max = i + p[i] ;
            }
        }
    }
    
    int main(){
        while( ~ scanf("%s",str) ){
            int len = strlen(str);
            for(int i=len; i>=0; i--){
                str[(i<<1)+1] = '#' ;
                str[(i<<1)+2] = str[i] ;
            }
            str[0] = '*' ;
            len = len * 2 + 2 ;
            manacher(str,len);
            int ans = 0 ;
            for(int i=0; i<len; i++){
                ans = max(p[i]-1,ans);
            }
            printf("%d
    ",ans);
        }
        return 0;
    }
    低调做人,高调做事。
  • 相关阅读:
    找水王
    环状二维数组最大子数组和
    用户模板
    课堂作业-电梯调度
    书店折扣问题
    《软件工程》读后感
    首尾相连的二维数组最大子数组求和
    梦断代码读后感(二)
    返回一个整数数组中最大子数组的和之测试
    首尾相连的一位数组最大子数组和
  • 原文地址:https://www.cnblogs.com/Asimple/p/5665719.html
Copyright © 2011-2022 走看看