hdu_3068_最长回文(Manacher)
题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=3068
题意:给你一个字符串,让你求最长的回文子串。
题解:数据量比较大,暴力O(n2)会超时,直接上马拉车,模版题。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<cstdio> 2 #include<cstring> 3 #define min(a,b) (a)>(b)?(b):(a) 4 #define max(a,b) (a)>(b)?(a):(b) 5 const int maxn = 110005;//字符串长度 6 struct Manacher{ 7 char str[maxn<<1]; 8 int p[maxn<<1],len,mx,id,tl,ans,i; 9 //bool pre[maxn],suf[maxn];//前(后)缀(前(后)p[i]-1个字符)是回文串 10 //void init(int len){for(int i=0;i<=len;i++)suf[i]=0,pre[i]=0;} 11 int maxlen(char *s){ 12 len=strlen(s),mx=0,id=0,tl=0,str[tl++]='$',str[tl++]='#'; 13 for(i=0;i<len;i++)str[tl++]=s[i],str[tl++]='#'; 14 for(i=2,str[tl]=0,ans=0;i<tl;i++){ 15 p[i]=mx>i?min(p[(id<<1)-i],mx-i):1; 16 while(str[i-p[i]]==str[i+p[i]])p[i]++; 17 if(i+p[i]>mx)mx=i+p[i],id=i; 18 ans=max(ans,p[i]); 19 //if(i-p[i]==0)pre[p[i]-1]=true; 20 //if(i+p[i]==len*2+2)suf[p[i]-1]=true; 21 } 22 return ans-1; 23 } 24 }M; 25 char s[maxn]; 26 int main(){ 27 while(~scanf("%s",s)){ 28 printf("%d\n",M.maxlen(s)); 29 } 30 return 0; 31 }