标签:
input | output |
---|---|
28 VOTEFORTHEGREATALBANIAFORYOU CHOOSETHEGREATALBANIANFUTURE |
THEGREATALBANIA |
ac代码
#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[400100]; int sa[400100],Rank[400100],rank2[400100],height[400100],c[400100],*x,*y; 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(char *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(char *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 ml,mr; int judge(int len,int k) { int i; for(i=1;i<len;i++) { if(height[i]>=k) { if(sa[i]>n&&sa[i-1]<=n||sa[i-1]>n&&sa[i]<=n) { ml=sa[i]; mr=sa[i]+height[i]; return 1; } } } return 0; } int main() { // int n; while(scanf("%d",&n)!=EOF) { int i,j; scanf("%s",str); str[n]=127; scanf("%s",str+n+1); int len=strlen(str); build_sa(str,len,128); getHeight(str,len); int l=0,r=n; while(l<=r) { int mid=(l+r)>>1; if(judge(len,mid)) { l=mid+1; } else r=mid-1; } for(j=ml;j<mr;j++) { // printf("%d",s[j]); printf("%c",str[j]); } printf("\n"); } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
URAL 题目1517. Freedom of Choice(后缀数组,求公共最长串)
标签:
原文地址:http://blog.csdn.net/yu_ch_sh/article/details/47837943