码迷,mamicode.com
首页 > 其他好文 > 详细

(最长回文串 模板) 最长回文 -- hdu -- 3068

时间:2015-10-01 20:26:26      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:

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

 

最长回文

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 12079    Accepted Submission(s): 4430


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 <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <limits>
#include <queue>
#include <stack>
#include <vector>
#include <map>

using namespace std;

#define N 244000
#define INF 0x3f3f3f3f
#define PI acos (-1.0)
#define EPS 1e-8
#define met(a, b) memset (a, b, sizeof (a))

char s[N], s1[N];
int p[N];

int manacher()
{
    int index=0, MaxLen = 0, ans=0;

    for(int i=2; s[i]; i++)
    {

        if(MaxLen > i) p[i] = min(MaxLen-i, p[2*index-i]);
        else p[i] = 1;
        while( s[i-p[i]] == s[i+p[i]] )
            p[i]++;

        if(i+p[i]>MaxLen)
        {
            MaxLen = p[i]+i;
            index = i;
        }

        ans = max(ans, p[i]);
    }

    return ans-1;
}

int main()
{
    while(scanf("%s", s1)!=EOF)
    {
        int len = strlen(s1), i;

        memset(s, 0, sizeof(s));

        s[0] = $;
        for(i=1; i<=len; i++)
        {
            s[i*2-1] = *;
            s[i*2]   =  s1[i-1];
        }
        s[i*2-1] = *;
        s[i*2] = \0;

        printf("%d\n", manacher());
    }
    return 0;
}
View Code

 

代码2

技术分享
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;

const int MAXN = 2e6+7;
const int oo = 1e9+37;

char s[MAXN];
int  p[MAXN];

int Manacher(int len)
{
    int id=0, Max=0;

    for(int i=2; i<len; i++)
    {
        p[i] = 1;

        if(p[id]+id > i)
            p[i] = min(p[id*2-i], p[id]+id-i);
        while(s[i+p[i]] == s[i-p[i]])
            p[i]++;
        if(p[id]+id < p[i]+i)
            id = i;

        Max = max(Max, p[i]-1);
    }

    return Max;
}

int main()
{
    int t = 1;

    while(scanf("%s", s), strcmp(s, "END"))
    {
        int N = strlen(s);

        for(int i=N; i>=0; i--)
        {
            s[i+i+2] = s[i];
            s[i+i+1] = #;
        }
        s[0] = $;

        printf("Case %d: %d\n", t++, Manacher(N+N+1));
    }

    return 0;
}
View Code

 

(最长回文串 模板) 最长回文 -- hdu -- 3068

标签:

原文地址:http://www.cnblogs.com/YY56/p/4851382.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!