题目地址:POJ 1226
将每一个字符串反转连接一次,再把所有字符串都连接起来,然后二分,找最大长度。注意与反转字符串之间不能直接相连。
代码如下:
#include <iostream>
#include <string.h>
#include <math.h>
#include <queue>
#include <algorithm>
#include <stdlib.h>
#include <map>
#include <set>
#include <stdio.h>
#include <string>
#include <time.h>
using namespace std;
#define LL long long
#define pi acos(-1.0)
#pragma comment(linker, "/STACK:1024000000")
const int mod=9901;
const int INF=0x3f3f3f3f;
const double eqs=1e-9;
const int MAXN=30000+300;
int ha[200], dp[200];
char st[101][200];
int wa[MAXN], wb[MAXN], wv[MAXN], ws1[MAXN], s[MAXN];
int sa[MAXN], rk[MAXN], height[MAXN];
int cmp(int *r, int a, int b, int l)
{
return r[a]==r[b]&&r[a+l]==r[b+l];
}
void getsa(int *r, int *sa, int n, int m)
{
int i, j, p, *x=wa, *y=wb, *t;
for(i=0; i<m; i++) ws1[i]=0;
for(i=0; i<n; i++) ws1[x[i]=r[i]]++;
for(i=1; i<m; i++) ws1[i]+=ws1[i-1];
for(i=n-1; i>=0; i--) sa[--ws1[x[i]]]=i;
for(j=1,p=1; p<n; j*=2,m=p) {
for(p=0,i=n-j; i<n; i++) y[p++]=i;
for(i=0; i<n; i++) if(sa[i]>=j) y[p++]=sa[i]-j;
for(i=0; i<n; i++) wv[i]=x[y[i]];
for(i=0; i<m; i++) ws1[i]=0;
for(i=0; i<n; i++) ws1[wv[i]]++;
for(i=1; i<m; i++) ws1[i]+=ws1[i-1];
for(i=n-1; i>=0; i--) sa[--ws1[wv[i]]]=y[i];
for(t=x,x=y,y=t,p=1,x[sa[0]]=0,i=1; i<n; i++)
x[sa[i]]=cmp(y,sa[i-1],sa[i],j)?p-1:p++;
}
}
void Calheight(int *r, int n)
{
int i, j, k=0;
for(i=1; i<=n; i++) rk[sa[i]]=i;
for(i=0; i<n; height[rk[i++]]=k) {
for(k?--k:0,j=sa[rk[i]-1]; r[i+k]==r[j+k]; k++) ;
}
}
int BS(int x, int n)
{
int low=0, high=n-1, mid, ans;
while(low<=high) {
mid=low+high>>1;
if(dp[mid]<=x) {
ans=mid;
low=mid+1;
} else high=mid-1;
}
return ans;
}
int Judge(char c)
{
if(c>='a'&&c<='z') return c-'a'+1;
return c-'A'+27;
}
int main()
{
int n, i, j, len, tmp, x, res, flag, t;
scanf("%d",&t);
while(t--) {
scanf("%d",&n);
tmp=0;
for(i=0; i<n; i++) {
scanf("%s",st[i]);
len=strlen(st[i]);
dp[i]=tmp;
for(j=0; j<len; j++) {
s[tmp++]=Judge(st[i][j]);
}
s[tmp++]=53+i*2;
for(j=len-1;j>=0;j--){
s[tmp++]=Judge(st[i][j]);
}
s[tmp++]=53+i*2+1;
}
s[tmp]=0;
getsa(s,sa,tmp+1,300);
Calheight(s,tmp);
int low=1, high=100, mid, ans=0;
while(low<=high) {
mid=low+high>>1;
memset(ha,0,sizeof(ha));
res=0;
for(i=1; i<=tmp; i++) {
if(height[i]>=mid) {
x=BS(sa[i],n);
if(!ha[x]){
res++;
ha[x]=1;
}
x=BS(sa[i-1],n);
if(!ha[x]) {
res++;
ha[x]=1;
}
if(res==n) break;
} else {
memset(ha,0,sizeof(ha));
res=0;
}
}
if(i<=tmp) {
ans=mid;
low=mid+1;
} else high=mid-1;
}
printf("%d\n",ans);
}
return 0;
}