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

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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章