HDU-3068 最长回文 Manacher算法

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

  直接用Manacher算法解决即可,先构造字符串,例如 abc -> $#a#b#c#  ,第一个‘$’是为了防止溢出字符串。其实也可以不构造字符串,直接去Manacher,具体做法是,当 i 为奇数时为‘#’,为偶数时再去比较。

 1 //STATUS:C++_AC_281MS_1348KB
 2 #include<stdio.h>
 3 #include<stdlib.h>
 4 #include<string.h>
 5 #include<math.h>
 6 #include<iostream>
 7 #include<string>
 8 #include<algorithm>
 9 #include<vector>
10 #include<queue>
11 #include<stack>
12 #include<map>
13 using namespace std;
14 #define LL __int64
15 #define pii pair<int,int>
16 #define Max(a,b) ((a)>(b)?(a):(b))
17 #define Min(a,b) ((a)<(b)?(a):(b))
18 #define mem(a,b) memset(a,b,sizeof(a))
19 #define lson l,mid,rt<<1
20 #define rson mid+1,r,rt<<1|1
21 const int N=110010,INF=0x3f3f3f3f,MOD=10000,STA=8000010;
22 const double DNF=1e13;
23 
24 char str[N<<1],s[N];
25 int p[N<<1];
26 int n,len;
27 
28 void Manacher(char *str,int *p)
29 {
30     int i,j,id,mx;
31     id=1,mx=1;
32     p[0]=p[1]=1;
33     for(i=2;i<n;i++){
34         p[i]=1;
35         if(mx>i){
36             p[i]=Min(p[(id<<1)-i],mx-i);
37         }
38         while(str[i+p[i]]==str[i-p[i]])p[i]++;
39         if(i+p[i]>mx){
40             id=i;
41             mx=i+p[i];
42         }
43     }
44 }
45 
46 void getstr(char *s)
47 {
48     int i;
49     str[0]='$';str[1]='#';
50     for(i=0;i<len;i++){
51         str[(i<<1)+2]=s[i];
52         str[(i<<1)+3]='#';
53     }
54     str[n]=0;
55 }
56 
57 int main()
58 {
59  //   freopen("in.txt","r",stdin);
60     int i,j,ans;
61     while(~scanf("%s",s))
62     {
63         len=strlen(s);
64         n=len*2+2;
65         getstr(s);
66         Manacher(str,p);
67 
68         ans=1;
69         for(i=2;i<n;i++){
70             ans=Max(ans,p[i]-1);
71         }
72 
73         printf("%d\n",ans);
74         getchar();
75         getchar();
76     }
77     return 0;
78 }

 

posted @ 2013-04-10 14:37  zhsl  阅读(364)  评论(0编辑  收藏  举报