标签:des style class blog code http
Time Limit: 15000MS | Memory Limit: 65536K | |
Total Submissions: 3695 | Accepted: 1338 |
Description
Input
Output
Sample Input
abcbabcbabcba abacacbaaaab END
Sample Output
Case 1: 13 Case 2: 6
题意:求最长回文子串
解法:当然,有很多种求法,什么SA,什么manacher,介于我最近在搞扩展kmp,就发个扩展kmp的吧。
讲解网址(不是我写的)http://hi.baidu.com/tcet030840zxp/item/71fd90024b1f92cd90571809
#include<cstdio> #include<cstdlib> #include<algorithm> #include<cmath> #include<cstring> using namespace std; int s[1000111]; int s1[1000111],s2[1000111],s3[1000111],s4[1000111]; int a[1000111],b[1000111],exEast[1000111],exWest[1000111]; int n,xzq,t; char c; bool p; void Read() { n=0; while(c=getchar(),(c<‘a‘||c>‘z‘)&&(c<‘A‘||c>‘Z‘)); if(c==‘E‘)p=false; s[++n]=c; while(c=getchar(),c>=‘a‘&&c<=‘z‘)s[++n]=c; } void Exkmp(int *s1,int *s2,int n1,int n2) { int len,k,i,l; len=0; for(i=2;i<=n1;i++){ if(len<i){ l=0; while(s1[i+l]==s1[1+l]&&i+l<=n1)l++; a[i]=l; } else{ if(a[i-k+1]<len-i+1)a[i]=a[i-k+1]; else{ l=len-i+1; while(s1[i+l]==s1[1+l]&&i+l<=n1)l++; a[i]=l; } } if(i+a[i]-1>len){ len=i+a[i]-1; k=i; } } len=0; for(i=1;i<=n2;i++){ if(len<i){ l=0; while(s2[i+l]==s1[1+l]&&i+l<=n2&&1+l<=n1)l++; b[i]=l; } else{ if(a[i-k+1]<len-i+1)b[i]=a[i-k+1]; else{ l=len-i+1; while(s2[i+l]==s1[1+l]&&i+l<=n2&&1+l<=n1)l++; b[i]=l; } } if(i+b[i]-1>len){ len=i+b[i]-1; k=i; } } } int Work(int l,int r) { if(l==r)return 1; int mid=(l+r)/2; int x,z,q,i,n1,n2,k; x=0; z=0; q=0; x=Work(l,mid); z=Work(mid+1,r); if(x>z)q=x; else q=z; n1=mid-l+1; for(i=l;i<=mid;i++){ k=i-l+1; s1[k]=s[i]; s3[n1-k+1]=s1[k]; } n2=r-mid; for(i=mid+1;i<=r;i++){ k=i-mid; s2[k]=s[i]; s4[n2-k+1]=s2[k]; } Exkmp(s3,s1,n1,n1); for(i=1;i<=n1;i++)exEast[i]=b[i]; Exkmp(s2,s3,n2,n1); for(i=1;i<=n1;i++)exWest[n1-i+1]=b[i]; exWest[0]=0; if(exWest[n1]*2>q)q=exWest[n1]*2; for(i=1;i<=n1;i++){ if(exEast[i]*2>=n1-i+1){ if(n1-i+1+exWest[i-1]*2>q)q=n1-i+1+exWest[i-1]*2; } } Exkmp(s3,s2,n1,n2); for(i=1;i<=n2;i++)exEast[i]=b[i]; Exkmp(s2,s4,n2,n2); for(i=1;i<=n2;i++)exWest[n2-i+1]=b[i]; if(exEast[1]*2>q)q=exEast[1]*2; exEast[n2+1]=0; for(i=1;i<=n2;i++){ if(exWest[i]*2>=i){ if(i+exEast[i+1]*2>q)q=i+exEast[i+1]*2; } } return q; } int main() { p=true; t=0; while(true){ t++; memset(s,0,sizeof(s)); Read(); if(p==false)break; xzq=Work(1,n); printf("Case %d: %d\n",t,xzq); } }
poj3974 最长回文串 exkmp,布布扣,bubuko.com
标签:des style class blog code http
原文地址:http://www.cnblogs.com/applejxt/p/3810498.html