求调(悬关)
  • 板块学术版
  • 楼主WZWZWZWY
  • 当前回复0
  • 已保存回复0
  • 发布时间2023/9/7 20:19
  • 上次更新2023/11/2 22:25:36
查看原帖
求调(悬关)
704668
WZWZWZWY楼主2023/9/7 20:19

题目求只看字母(大写小写互通)的最长回文的长度,并输出长度和回文串

#include <iostream>
using namespace std;
const int MAX=22000005;
char c[MAX];
string s;
int cnt,p[MAX],maxright,mid,ans;
int Map[MAX],Mapcnt,starti;
void reads(){
	char cs;
	c[0]='.'; 
	while((cs<'a'||cs>'z')&&(cs<'A'||cs>'Z')) cs = getchar();
	while(cs!='\n'){
		s = s+cs;
		if ((cs>='a'&&cs<='z')||(cs>='A'&&cs<='Z')){
			if (cs>='A'&&cs<='Z')cs=cs-'A'+'a';
			c[++cnt]='#';
			Map[cnt] = s.length()-1;
			c[++cnt]=cs;
			Map[cnt] = s.length()-1;
		}
		cs=getchar();
	}
	
	c[++cnt]='#';
}
void manacher(){
	for (int i = 2; i <= cnt-1; i++){
		if (i <= maxright) p[i] = min(p[(mid<<1)-i],maxright-i+1);
		else p[i]=1;
		while(c[i-p[i]]==c[i+p[i]])++p[i];
		if (i+p[i]-1>maxright){maxright=i+p[i]-1;mid=i;}
		if (p[i]>ans){
			ans = p[i];
			starti = i;
		}
	}
}
int main()
{
	reads();
	manacher();
	printf("%d\n",ans-1);
	for (int i = Map[starti-ans/2]; i <= Map[starti+ans/2]; i++) cout << s[i];
}

ans表示最长回文的长度

starti记录 答案这个字符串 的中间位置在只含有字母的c串中对应的下标

Map用来记录c映射到s的下标,应该是这个地方出了点问题QAQ

样例

Madam, I'm Adam

输出:

11
Madam, I'm Adam
2023/9/7 20:19
加载中...