HDU 3068 最长回文(马拉车模板题)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/baodream/article/details/81945586

题目链接:http://hdu.hustoj.com/showproblem.php?pid=3068

Problem 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

题目思路:马拉车模板题

代码:

#include<cstdio>
#include<cmath>
#include<cstring>
#include<string>
#include<cstdlib>
#include<algorithm>
#include<iostream>
#include<queue>
#include<stack>
#include<map>

using namespace std;

#define FOU(i,x,y) for(int i=x;i<=y;i++)
#define FOD(i,x,y) for(int i=x;i>=y;i--)
#define MEM(a,val) memset(a,val,sizeof(a))
#define PI acos(-1.0)

const double EXP = 1e-9;
typedef long long ll;
typedef unsigned long long ull;
const int INF = 0x3f3f3f3f;
const ll MINF = 0x3f3f3f3f3f3f3f3f;
const double DINF = 0xffffffffffff;
const int mod = 1e9+7;

const int N = 110005;
char str[N],s[N*2];
int p[N*2],len1,len2;  //p[i]表示以t[i]字符为中心的回文子串的半径

/*s[i]: # 1 # 2 # 2 # 1 # 2 # 2 #
p[i]:     1 2 1 2 5 2 1 6 1 2 3 2 1*/

init(){
    s[0] = '$';  //这里是一个用不大的字符
    s[1] = '#';
    len1 = strlen(str);
    for(int i=0;i<len1;i++){
        s[i*2+2] = str[i];
        s[i*2+3] = '#';
    }
    len2 = len1*2+2;
    s[len2] = '@';  //另一个不会出现的字符,与str[0]不同,防止匹配越界
}

void Manacher(){
    init();         //字符串翻倍
    int id = 0, mx = 0;
    int ans = 0;   //得到最长回文长度
    for(int i = 1;i < len2;i++){
        if(mx > i)
            p[i] = min(p[2*id-i],mx-i);
        else
            p[i] = 1;
        while(s[i+p[i]] == s[i-p[i]]) p[i]++;
        if(mx < p[i]+i){
            id = i;
            mx = p[i]+i;
        }
        ans = max(ans,p[i]-1);  //减1才是最后答案
    }
    printf("%d\n",ans);
}


int main()
{
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    std::ios::sync_with_stdio(false);
    while(~scanf(" %s",str)){
        Manacher();
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/baodream/article/details/81945586