POJ-3974 Palindrome Manacher算法
题目链接:http://poj.org/problem?id=3974
Manacher算法效率真不错,用后缀数组A的都沙茶了。。
1 //STATUS:C++_AC_235MS_10904KB 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=1000010,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,ca=1; 61 while(~scanf("%s",s)) 62 { 63 len=strlen(s); 64 if(len==3 && s[0]=='E' && s[1]=='N' && s[2]=='D')break; 65 n=len*2+4; 66 getstr(s); 67 Manacher(str,p); 68 69 ans=1; 70 for(i=2;i<n;i++){ 71 ans=Max(ans,p[i]-1); 72 } 73 74 printf("Case %d: %d\n",ca++,ans); 75 } 76 return 0; 77 }