HDU 3068 最长回文(manacher模板题)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3068 

题目大意:求字符串s中最长的回文子串

解题思路:manacher模板

代码

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<algorithm>
 4 #include<cstring>
 5 using namespace std;
 6 const int N=1e6+5;
 7 
 8 int len1,len2;
 9 int p[N];
10 char s[N],str[N];
11 
12 void init(){
13     str[0]='$';
14     str[1]='#';
15     for(int i=0;i<len1;i++){
16         str[i*2+2]=s[i];
17         str[i*2+3]='#';
18     }
19     len2=len1*2+2;
20     str[len2]='%';
21 }
22 
23 void manacher(){
24     int id=0,mx=0;
25     for(int i=1;i<len2;i++){
26         if(mx>i) p[i]=min(p[2*id-i],mx-i);
27         else p[i]=1;
28         while(str[i+p[i]]==str[i-p[i]])
29             p[i]++;
30         if(p[i]+i>mx){
31             mx=p[i]+i;
32             id=i;
33         }
34     }
35 }
36 
37 int main(){
38     while(~scanf("%s",s)){
39         len1=strlen(s);
40         init();
41         manacher();
42         int ans=0;
43         for(int i=0;i<len2;i++){
44             ans=max(ans,p[i]);
45         }
46         printf("%d\n",ans-1);
47     }
48     return 0;
49 }

 

posted @ 2018-03-04 11:21  Yeader  阅读(111)  评论(0编辑  收藏  举报