1297. Palindrome
Memory limit: 64 MB
In addition, it is reasonable to assume that the agent will be sending a very long message, so John has simply to find the longest message satisfying the mentioned property.
Input
Output
Sample
input | output |
---|---|
ThesampletextthatcouldbereadedthesameinbothordersArozaupalanalapuazorA |
ArozaupalanalapuazorA |
Problem Source: IX Open Collegiate Programming Contest of the High School Pupils (13.03.2004)
My submissions All submissions (19930) All
accepted submissions (6214) Solutions rating (4095)
ac代码
首先肯定是要把原字符的逆序串接到原字符串的后面。然后便是从0~~len扫描这个字符串,如果第i个位置是一个回文的中心。然后求出i个i相应位置的lca的最大值就可以。每次枚举时要分奇偶两种情况考虑。
#include<stdio.h> #include<string.h> #include<algorithm> #include<iostream> #define min(a,b) (a>b?b:a) #define max(a,b) (a>b?a:b) using namespace std; char str[3030]; int sa[3030],Rank[3030],rank2[3030],height[3030],c[3030],*x,*y,s[3030]; int n; void cmp(int n,int sz) { int i; memset(c,0,sizeof(c)); for(i=0;i<n;i++) c[x[y[i]]]++; for(i=1;i<sz;i++) c[i]+=c[i-1]; for(i=n-1;i>=0;i--) sa[--c[x[y[i]]]]=y[i]; } void build_sa(int *s,int n,int sz) { x=Rank,y=rank2; int i,j; for(i=0;i<n;i++) x[i]=s[i],y[i]=i; cmp(n,sz); int len; for(len=1;len<n;len<<=1) { int yid=0; for(i=n-len;i<n;i++) { y[yid++]=i; } for(i=0;i<n;i++) if(sa[i]>=len) y[yid++]=sa[i]-len; cmp(n,sz); swap(x,y); x[sa[0]]=yid=0; for(i=1;i<n;i++) { if(y[sa[i-1]]==y[sa[i]]&&sa[i-1]+len<n&&sa[i]+len<n&&y[sa[i-1]+len]==y[sa[i]+len]) x[sa[i]]=yid; else x[sa[i]]=++yid; } sz=yid+1; if(sz>=n) break; } for(i=0;i<n;i++) Rank[i]=x[i]; } void getHeight(int *s,int n) { int k=0; for(int i=0;i<n;i++) { if(Rank[i]==0) continue; k=max(0,k-1); int j=sa[Rank[i]-1]; while(s[i+k]==s[j+k]) k++; height[Rank[i]]=k; } } int minv[3010][20],lg[3030]; void init_lg() { int i; lg[1]=0; for(i=2;i<2020;i++) { lg[i]=lg[i>>1]+1; } } void init_RMQ(int n) { int i,j,k; for(i=1;i<=n;i++) { minv[i][0]=height[i]; } for(j=1;j<=lg[n];j++) { for(k=0;k+(1<<j)-1<=n;k++) { minv[k][j]=min(minv[k][j-1],minv[k+(1<<(j-1))][j-1]); } } } int lcp(int l,int r) { l=Rank[l]; r=Rank[r]; if(l>r) swap(l,r); l++; int k=lg[r-l+1]; return min(minv[l][k],minv[r-(1<<k)+1][k]); } int main() { while(scanf("%s",str)!=EOF) { int n=0,i; int len=strlen(str); for(i=0;i<len;i++) { s[n++]=str[i]; } s[n++]=127; for(i=len-1;i>=0;i--) s[n++]=str[i]; s[n]=0; build_sa(s,n+1,128); getHeight(s,n); init_lg(); init_RMQ(n); int ans=-1,st; for(i=0;i<len;i++) { int temp=lcp(i,n-i-1); if(temp*2-1>ans) { ans=temp*2-1; st=i-temp+1; } temp=lcp(i,n-i); if(temp*2>ans) { ans=temp*2; st=i-temp; } } // printf("%d %d\n",ans,st); if(ans==1) printf("%c\n",str[0]); else { for(i=0;i<ans;i++) { printf("%c",str[i+st]); } printf("\n"); } } }