http://cogs.pro:8080/cogs/problem/problem.php?pid=pxXNxQVqP
题意:给m个单词,让求最长公共子串的长度。
思路:先把所有单词合并成一个串(假设长度是n,包含分隔符),中间用不同符号分隔,求出high[i](表示rk为i的和rk为i+1的后缀的最长公共前缀),然后二分答案ans,对于rk从1扫到n,如果有一段连续的rk值使得high[rk]>=ans且这段的串盖满了每个单词块,那么ans成立,即最终答案大于ans。
#include <algorithm> #include <iostream> #include <cstdlib> #include <cstring> #include <cstdio> #include <cmath> using namespace std; const int N=20005; int s[N],n=0,k,tmp[N],sa[N],rk[N],high[N],color[N],m,l[6];char S[6][2005]; bool comp(int i,int j){ if(rk[i]!=rk[j])return rk[i]<rk[j]; int ri=i+k<=n?rk[i+k]:-1; int rj=j+k<=n?rk[j+k]:-1; return ri<rj; } void Getsa(){ for(int i=1;i<=n;i++){ sa[i]=i;rk[i]=s[i]; } for(k=1;k<=n;k<<=1){ sort(sa+1,sa+n+1,comp); for(int i=1;i<=n;i++)tmp[sa[i]]=tmp[sa[i-1]]+comp(sa[i-1],sa[i]); for(int i=1;i<=n;i++)rk[i]=tmp[i]; } } void Gethight(){ int j,h=0; for(int i=1;i<=n;i++){ j=sa[rk[i]-1]; if(h)h--; for(;j+h<=n && i+h<=n;h++)if(s[i+h]!=s[j+h])break; high[rk[i]-1]=h; } } void prework(int m){ int p=0; for(int i=1;i<=m;i++){ for(int j=1;j<=l[i];j++) p++,color[p]=i; p++; } } bool d[8]; bool check(int lim){ int p,ret; for(int i=1;i<n;i++){ if(high[i]>=lim){ p=i; while(p<n && high[p+1]>=lim)p++;p++; for(int j=1;j<=m;j++)d[j]=false; for(int j=i;j<=p;j++)d[color[sa[j]]]=true; ret=p;p=1; while(p<=m && d[p])p++; if(p==m+1)return true; i=ret; } } return false; } int main() { freopen("pow.in","r",stdin); freopen("pow.out","w",stdout); int r=2e8; scanf("%d",&m); for(int i=1;i<=m;i++){ scanf("%s",S[i]); l[i]=strlen(S[i]); if(l[i]<r)r=l[i]; for(int j=0;j<l[i];j++)s[++n]=S[i][j]; s[++n]=i; } Getsa();Gethight();prework(m); int l=0,mid,ans; while(l<=r){ mid=(l+r)>>1; if(check(mid))ans=mid,l=mid+1; else r=mid-1; } printf("%d ",ans); return 0; }