【HDU - 3068】最长回文(Manacher算法,马拉车算法求最长回文子串)

版权声明:欢迎学习我的博客,希望ACM的发展越来越好~ https://blog.csdn.net/qq_41289920/article/details/83536527

题干:

给出一个只由小写英文字符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

解题报告:

    裸的马拉车算法,一定注意修改后的数组需要开二倍就好了,,,不然会RE但是我也不知道为什么HDUoj报TLE很迷。。但是这题好像可以暴力啊。。跑出来都是200多ms。。

AC代码:

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<queue>
#include<map>
#include<vector>
#include<set>
#include<string>
#include<cmath>
#include<cstring>
#define ll long long
#define pb push_back
#define pm make_pair
#define fi first
#define se second
using namespace std;
const int MAX = 2e5 + 5;
int top;
char s[110005],str[110005<<1];
int p[120005<<1];
int manacher() {
	if(top == 0) return 0 ;
	int maxx = -1;
	int c = -1,r = -1;
	for(int i = 1; i<top; i++) {
		p[i] = r>i ? min(p[2*c-i],r-i) : 1;
//		while(i+p[i]<top && i-p[i] > -1) {
//			if(str[i+p[i]] == str[i-p[i]]) p[i]++;
//			else break;			
//		}
		for(;str[i-p[i]] == str[i+p[i]];p[i]++);
		if(i+p[i] > r) {
			r = i+p[i];
			c=i;
		}
		maxx = max(maxx,p[i]);
		
	}
	return maxx-1;
}
int main()
{
	while(~scanf("%s",s)) {
		int len = strlen(s);
		top=0;
		str[top++] = '@';
		for(int i = 0; i<len; i++) {
			str[top++] = '#';
			str[top++] = s[i];
		}
		str[top++] = '#';
		str[top] = '\0';
//		printf("%s\n",str);
		printf("%d\n",manacher());
	} 
	return 0 ;
 }

猜你喜欢

转载自blog.csdn.net/qq_41289920/article/details/83536527