欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

[Luogu3805] 【模板】manacher算法 [Manacher][PAM]

程序员文章站 2024-03-09 09:03:59
...

Link
Luogu - https://www.luogu.org/problemnew/show/P3805


板子。
第一次踩了 SIGTRAP 纪念一下
但是我并没有写 PAM


#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<cmath>
#include<ctime>
#include<cctype>
using namespace std;
#define R register
const int MAXN = 22e6 + 5;
int n, Rad[MAXN];
string S;
void Manacher()
{
	for (R int Right = -1, Mid = -1, Tmp = -1, i = 0; i < n; ++i)
	{
		if (Right <= i)
		{
			while ((i + Rad[i] < n - 1) && (i - Rad[i] > 0) && (S[i - Rad[i] - 1] == S[i + Rad[i] + 1])) ++Rad[i];
			Right = i + Rad[i];
			Mid = i;
		}
		else
		{
			Tmp = i + Rad[(Mid << 1) - i - Rad[i]];
			if (Tmp > Right)
			{
				Rad[i] = Right - i;
			}
			else
			{
				Rad[i] = Tmp - i;
				if (Tmp == Right)
				{
					while ((i + Rad[i] < n - 1) && (i - Rad[i] > 0) && (S[i - Rad[i] - 1] == S[i + Rad[i] + 1])) ++Rad[i];
					Right = i + Rad[i];
					Mid = i;
				}
			}
		}
	}
}
int main()
{
	cin >> S;
	n = S.size();
	S.reserve((n<<1)|1);
	for (R int i = n - 1; i >= 0; --i)
	{
		S[i << 1 | 1] = S[i];
		S[i << 1] = '#';
	}
	n <<= 1;
	++n;
	S[n-1] = '#';
	Manacher();
	int Ans = 0;
	for (R int i = 0; i < n; ++i)
	{
		Rad[i] = ((Rad[i] >> 1) << 1) + (i & 1);
		if (Rad[i] > Ans) Ans = Rad[i];
	}
	cout << Ans;
	return 0;
}