P3805 【模板】manacher:回文字符串类题目

https://www.luogu.com.cn/problem/P3805
板子题

比较模式的代码(书上整理):

#include<iostream>
#include<vector>
#include<algorithm>
#include<math.h>
#include<sstream>
#include<string>
#include<string.h>
#include<iomanip>
#include<map>
#include<queue>
#include<limits.h>
#include<climits>
using namespace std;
typedef long long ll;


const int N = 11000002;
int n, P[N *2];
char a[N], S[N *2];
void change()//功能:改成"$#x#x#^",比较值得注意的是:前后的末尾都是#再结束。
{
	n = strlen(a);//不要用sizeof!
	S[0] = '$';
	int k = 2;
	S[1] = '#';
	for (int i = 0; i < n; i++)
	{
		S[k++] = a[i];
		S[k++] = '#';
	}
	S[k++] = '^';
	n = k;
}
void manacher()
{
	int R=0, C;
	for (int i = 0; i < n; i++)
	{
		if (i < R)P[i] = min(P[C * 2 - i], P[C] + C - i);//核心,比大小
		else P[i] = 1;
		while (S[i + P[i]] == S[i - P[i]])P[i]++;//左右开弓
		if (i + P[i] > R)
		{
			R = i + P[i];
			C = i;
		}
	}
}


int main()
{
	scanf("%s", a);
	change();
	manacher();
	int ans = 1;
	for (int i = 0; i < n; i++)ans = max(ans, P[i]);
	cout << ans -1 ;
	return 0;
}

posted on 2024-03-10 17:17  WHUStar  阅读(1)  评论(0编辑  收藏  举报