hdu 3068---最長回文

2607 ワード

最長回文
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組を超えず、各組は1行の小文字の英語文字a,b,c...y,zからなる文字列Sとして入力される.
2組のcaseの間は空の行で区切られています(この空の行は処理されません).
文字列長len<=110000
 
Output
各行に1つの整数xは、caseのグループに対応する、そのグループのcaseの文字列に含まれる最長の回文長を表す.
 
Sample Input

   
   
   
   
aaaa abab

 
Sample Output

   
   
   
   
4 3

 
Source
2009 Multi-University Training Contest 16 - Host by NIT
 
Recommend
lcy   |   We have carefully selected several similar problems for you:   3065  3067  3063  3064  3062
manacherで解決する
/*************************************************************************
    > File Name: hdu3068.cpp
    > Author: ALex
    > Mail: [email protected] 
    > 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
", 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; }