ural1297 求最长回文子串 | 后缀数组
#include<cstdio> #include<algorithm> #include<cstring> #define N 20005 using namespace std; int buf1[N],buf2[N],sa[N],rnk[N],buc[N],n,height[N],ans,Log[N],pos,Min[N][25]; char s[N]; void suffix_sort() { int *x=buf1,*y=buf2,m=1000; for (int i=0;i<m;i++) buc[i]=0; for (int i=1;i<=n;i++) buc[x[i]=s[i]]++; for (int i=1;i<=m;i++) buc[i]+=buc[i-1]; for (int i=n;i;i--) sa[buc[x[i]]--]=i; for (int k=1;k<=n;k<<=1) { int p=0; for (int i=n-k+1;i<=n;i++) y[++p]=i; for (int i=1;i<=n;i++) if (sa[i]>k) y[++p]=sa[i]-k; for (int i=0;i<=m;i++) buc[i]=0; for (int i=1;i<=n;i++) buc[x[y[i]]]++; for (int i=1;i<=m;i++) buc[i]+=buc[i-1]; for (int i=n;i;i--) sa[buc[x[y[i]]]--]=y[i]; swap(x,y),x[sa[1]]=p=1; for (int i=2;i<=n;i++) if (y[sa[i-1]]==y[sa[i]] && y[sa[i-1]+k]== y[sa[i]+k]) x[sa[i]]=p; else x[sa[i]]=++p; if ((m=p)>=n) break; } for (int i=1;i<=n;i++) rnk[sa[i]]=i; for (int i=1,j,k=0;i<=n;i++) { if (rnk[i]==1) continue; if (k) k--; j=sa[rnk[i]-1]; while (s[i+k]==s[j+k] && i+k<=n && j+k<=n) k++; height[rnk[i]]=k; } } void InitRmq() { for (int i=1;i<=n;i++) Min[i][0]=height[i]; for (int j=1;j<=20;j++) for (int i=1;i+(1<<j)-1<=n;i++) Min[i][j]=min(Min[i][j-1],Min[i+(1<<j-1)][j-1]); } int Query(int x,int y) { int i=rnk[x],j=rnk[y]; if (i>j) swap(i,j); int len=Log[j-i]; return min(Min[i+1][len],Min[j-(1<<len)+1][len]); } int main() { scanf("%s",s+1); n=strlen(s+1); if (n==1) { puts(s+1); return 0; } s[n+1]='#'; for (int i=1;i<=n;i++) s[2*n+2-i]=s[i]; n=n*2+1; suffix_sort(); for (int i=2;i<=n;i++) Log[i]=Log[i>>1]+1; InitRmq(); for (int i=1;i<=(n-1)/2;i++) { int tmp=Query(i,n-i+2); if (tmp*2>ans) ans=tmp*2,pos=i-tmp; tmp=Query(i,n-i+1); if (tmp*2-1>ans) ans=tmp*2-1,pos=i-tmp+1; } for (int i=1;i<=ans;i++) putchar(s[i+pos-1]); return 0; }