现在的位置: 首页 > 综合 > 正文

hdu3068—最长回文

2019年02月15日 ⁄ 综合 ⁄ 共 1589字 ⁄ 字号 评论关闭

最长回文

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

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
 

Source
 

Recommend
lcy   |   We have carefully selected several similar problems for you:  3065 3067 3063 3064 3062

用manacher解决

/*************************************************************************
    > File Name: hdu3068.cpp
    > Author: ALex
    > Mail: zchao1995@gmail.com 
    > Created Time: 2015年02月01日 星期日 21时27分08秒
 ************************************************************************/

#include <map>
#include <set>
#include <queue>
#include <stack>
#include <vector>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;

const double pi = acos(-1);
const int inf = 0x3f3f3f3f;
const double eps = 1e-15;
typedef long long LL;
typedef pair <int, int> PLL;
const int N = 210010;

char str[N];
char mat[N];
int p[N];

void manacher (int cnt)
{
	memset (p, 0, sizeof(p));
	int MaxId  = 0, id;
	int MaxL = 0;
	for (int i = 1; i < cnt; ++i)
	{
		if (MaxId > i)
		{
			p[i] = min (p[2 * id - i], MaxId - i);
		}
		else
		{
			p[i] = 1;
		}
		while (str[i + p[i]] == str[i - p[i]])
		{
			++p[i];
		}
		if (p[i] + i > MaxId)
		{
			MaxId = p[i] + i;
			id = i;
		}
		if (p[i] - 1 > MaxL)
		{
			MaxL = p[i] - 1;
		}
	}
	printf("%d\n", MaxL);
}

int main ()
{
	while (~scanf("%s", mat))
	{
		int n = strlen (mat);
		int cnt = 2;
		for (int i = 0; i < n; ++i)
		{
			str[cnt++] = mat[i];
			str[cnt++] = '#';
		}
		str[0] = '?';
		str[1] = '#';
		str[cnt] = 0;
		manacher (cnt);
	}
	return 0;
}

抱歉!评论已关闭.