# [POJ3294]Life Forms（后缀数组+二分）

## 题解

①n=1的时候要特判
②每一个height都不能超过它本身表示的字符串的长度

## 代码

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
#define N 200005

int T,k,n,m,la,Max;
char a[N],s[N];
int *x,*y,X[N],Y[N],c[N],sa[N],height[N],rank[N];
int str[N],is_end[N],flag[N],ans[N];

void clear()
{
k=n=m=la=Max=0;
memset(a,0,sizeof(a));memset(s,0,sizeof(s));
memset(X,0,sizeof(X));memset(Y,0,sizeof(Y));memset(c,0,sizeof(c));
memset(sa,0,sizeof(sa));memset(height,0,sizeof(height));memset(rank,0,sizeof(rank));
memset(str,0,sizeof(str));memset(is_end,0,sizeof(is_end));memset(flag,0,sizeof(flag));memset(ans,0,sizeof(ans));
}
void build_sa()
{
m=200;
x=X,y=Y;
for (int i=0;i<m;++i) c[i]=0;
for (int i=0;i<n;++i) ++c[x[i]=s[i]];
for (int i=1;i<m;++i) c[i]+=c[i-1];
for (int i=n-1;i>=0;--i) sa[--c[x[i]]]=i;

for (int k=1;k<=n;k<<=1)
{
int p=0;
for (int i=n-k;i<n;++i) y[p++]=i;
for (int i=0;i<n;++i) if (sa[i]>=k) y[p++]=sa[i]-k;

for (int i=0;i<m;++i) c[i]=0;
for (int i=0;i<n;++i) ++c[x[y[i]]];
for (int i=1;i<m;++i) c[i]+=c[i-1];
for (int i=n-1;i>=0;--i) sa[--c[x[y[i]]]]=y[i];

swap(x,y);
p=1,x[sa[0]]=0;
for (int i=1;i<n;++i)
x[sa[i]]=y[sa[i-1]]==y[sa[i]]&&((sa[i-1]+k<n?y[sa[i-1]+k]:-1)==(sa[i]+k<n?y[sa[i]+k]:-1))?p-1:p++;
if (p>n) break;
m=p;
}
}
void build_height()
{
for (int i=0;i<n;++i) rank[sa[i]]=i;
int k=0;height[0]=0;
for (int i=0;i<n;++i)
{
if (!rank[i]) continue;
if (k) --k;
int j=sa[rank[i]-1];
while (i+k<n&&j+k<n&&s[i+k]==s[j+k]) ++k;
height[rank[i]]=k;
}
}
bool check(int mid)
{
bool pd=false;
int last=T-1;
for (int i=T;i<=n;++i)
{
if (height[i]<mid||i==n)
{
int cnt=0;
for (int j=last;j<i;++j)
{
if (!flag[str[sa[j]]]) ++cnt;
++flag[str[sa[j]]];
}
if (cnt>=k)
{
if (!pd) pd=true,ans[0]=0;
ans[++ans[0]]=last;
}
for (int j=last;j<i;++j)
--flag[str[sa[j]]];
last=i;
}
}
return pd;
}
int find()
{
int l=0,r=Max,mid,ans=0;
while (l<=r)
{
mid=(l+r)>>1;
if (check(mid)) ans=mid,l=mid+1;
else r=mid-1;
}
return ans;
}
int main()
{
while (~scanf("%d\n",&T))
{
if (!T) break;
clear();
k=T/2+1;
for (int i=1;i<=T;++i)
{
gets(a);la=strlen(a);
if (k==1)
{
if (la>Max) ans[0]=1,ans[1]=n+1;
else if (la==Max) ans[++ans[0]]=n+1;
}
Max=max(Max,la);
for (int j=0;j<la;++j)
s[n++]=a[j],str[n-1]=i;
if (i!=T) s[n++]='\$',str[n-1]=i;
is_end[i]=n-1;
}
if (k==1)
{
for (int i=1;i<=ans[0];++i)
{
for (int j=0;j<Max;++j)
putchar(s[sa[i]+j]);putchar('\n');
puts("");
}
continue;
}
is_end[T]=n;
build_sa();
build_height();
for (int i=T-1;i<n;++i)
height[i]=min(height[i],is_end[str[sa[i]]]-sa[i]);
int len=find();
if (!len)
{
puts("?");
puts("");
continue;
}
for (int i=1;i<=ans[0];++i)
{
for (int j=0;j<len;++j)
putchar(s[sa[ans[i]]+j]);putchar('\n');
}
puts("");
}
}