【模板】Manacher 回文串

推荐两个讲得很好的博客:

  http://blog.sina.com.cn/s/blog_70811e1a01014esn.html

  https://segmentfault.com/a/1190000003914228

 1 #include<cstring>
 2 #include<cstdio>
 3 #include<algorithm>
 4 #define N (22000010) 
 5 using namespace std;
 6 int n, ans, mid, mx; 
 7 int p[N];
 8 char tmp[N],s[N];
 9 inline int max(int a, int b){return a>b?a:b;}
10 int main(){
11     scanf("%s", tmp+1); n=strlen(tmp+1);
12     for(int i=1;i<=n;i++) s[i<<1]=tmp[i], s[i<<1|1]='#'; 
13     n=(n<<1)+2; 
14     s[1]=s[n]='#'; 
15     ans=mid=mx=0;
16     for(int i=1;i<=n;i++){
17         if(mx>i) p[i]=min(p[(mid<<1)-i],mx-i);
18             else p[i]=1;
19         while(s[i-p[i]]==s[i+p[i]]) p[i]++;
20         if(p[i]+i>mx) mx=p[i]+i, mid=i;
21         ans=max(ans, p[i]);
22     }
23     return printf("%d\n", ans-1),0;
24 }
View Code

 

洛谷 3805

posted @ 2018-01-22 14:16  Driver_Lao  阅读(145)  评论(0编辑  收藏  举报