Manacher算法

Manacher算法

用于寻找给定字符串中的最长回文子串。

模板(待修改)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
Manacher
*/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
//using namespace std;
#define maxn 2*11000003
char s[maxn];
int lens=0,spread[maxn];
int maxl,maxid;

void Manacher()
{
	int id=0,rbound=0;
	maxid=0;maxl=0;
	int i=0;
	for(;i<=lens;++i)
	{
		if(i<rbound)
		{
			int j=2*id-i;
			if(spread[j]<rbound-i)
			{
				spread[i]=spread[j];
			}
			else spread[i]=rbound-i;
		}//else spread[i]=0
		
		while
		( i-spread[i]-1>=0
		&&i+spread[i]+1<=lens
		&&s[i+spread[i]+1]==s[i-spread[i]-1])
		{
			++spread[i];
		}
		if(i+spread[i]>rbound)
			rbound=i+spread[i],id=i;
		if(spread[i]>maxl)
			maxl=spread[i],maxid=i;
	}
}
int main()
{
	s[0]=1;
	while(scanf("%c",&s[++lens])!=EOF)
	{
		if(s[lens]!='\n')s[++lens]=1;
		else 
		{
			s[lens]='\0';
			break;
		}
	}
	--lens;
	Manacher();
	printf("%d",(maxl));
	return 0;
}

例题:luogu1210USACO6.2.1(原1.3.3))

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*
Manacher
luogu1210
*/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
using namespace std;
char ss[42003],s[42003],real[4203],ans[42003];
int Map[42003];
int lenss=0,lens=0,lenreal=0,spread[42003];
int maxl,maxid;
void change()
{
	for(int i=0;i<=lenreal-1;++i)
	{
		if(real[i]>=97&&real[i]<=122)
			ss[lenss++]=real[i],Map[lenss-1]=i;
		else if(real[i]>=65&&real[i]<=90)
			ss[lenss++]=real[i]+32,Map[lenss-1]=i;	
	}
	ss[lenss]='\0';
}
void addChar()
{
	for(int i=0;i<=lenss-1;++i)
	{
		s[2*i+1]=ss[i];
		s[2*i]='#';
	}
	s[2*lenss+1]='\0';
	s[2*lenss]='#';
	lens=2*lenss+1;
}
inline int mapss(int pos)
{
	return (pos-1)>>1;
}
void Manacher()
{
	int id=0,rbound=0;
	maxid=0;maxl=0;
	for(int i=0;i<=lens-1;++i)
	{
		if(i<rbound)
		{
			int j=2*id-i;
			if(spread[j]<rbound-i)
			{
				spread[i]=spread[j];
			}
			else spread[i]=rbound-i;
		}//else spread[i]=0
		
		while
		( i-spread[i]-1>=0
		&&i+spread[i]+1<=lens-1
		&&s[i+spread[i]+1]==s[i-spread[i]-1])
		{
			++spread[i];
		}
		if(i+spread[i]>rbound)
			rbound=i+spread[i],id=i;
		if(spread[i]>maxl)
			maxl=spread[i],maxid=i;
	}
}
//#undef DEBUG
int main()
{
	freopen("1210.in","r",stdin);
	//freopen("1210.out","w",stdout);
	while(scanf("%c",&real[lenreal])!=EOF)
		++lenreal;
	lenreal='\0';
	lenreal=strlen(real);
	change();
	addChar();
	Manacher();
	printf("%d\n",mapss(maxid+maxl-1)-mapss(maxid-maxl+1)+1);
	int l=Map[mapss(maxid-maxl+1)],
		r=Map[mapss(maxid+maxl-1)];
	for(int i=l;i<=r;++i)
	{
		ans[i-l]=real[i];
	}
	ans[r-l+1]='\0';
	printf("%s\n",ans);
	return 0;
}

推荐

0%