Substrings
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 11987 | Accepted: 4198 |
Description
You are given a number of case-sensitive strings of alphabetic characters, find the largest string X, such that either X, or its inverse can be found as a substring of any of the given strings.
Input
The first line of the input contains a single integer t (1 <= t <= 10), the number of test cases, followed by the input data for each test case. The first line of each test case contains a single integer n (1 <= n <= 100), the number of given strings, followed by n lines, each representing one string of minimum length 1 and maximum length 100. There is no extra white space before and after a string.
Output
There should be one line per test case containing the length of the largest string found.
Sample Input
2 3 ABCD BCDFF BRCD 2 rose orchid
Sample Output
2 2
这道题是将所有字符串原串和反转后的拼接,二份答案并对height数组分组,统计某个字串是否在所有字符串或其反串(两者至少有一个)中出现。
代码:
#include<cstdio>
#include<iostream>
#include<cstring>
#define Maxn 10010
using namespace std;
int r[Maxn],sa[Maxn],rk[Maxn],height[Maxn];
int wa[Maxn],wb[Maxn],rs[Maxn],wv[Maxn];
int cmp(int *r,int a,int b,int l){
return r[a]==r[b]&&r[a+l]==r[b+l];
}
void da(int n,int m){
int i,j,p,*x=wa,*y=wb;
for(i=0;i<m;i++) rs[i]=0;
for(i=0;i<n;i++) rs[x[i]=r[i]]++;
for(i=1;i<m;i++) rs[i]+=rs[i-1];
for(i=n-1;i>=0;i--) sa[--rs[x[i]]]=i;
for(j=1,p=1;p<n;j<<=1,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<m;i++) rs[i]=0;
for(i=0;i<n;i++) rs[wv[i]=x[y[i]]]++;
for(i=1;i<m;i++) rs[i]+=rs[i-1];
for(i=n-1;i>=0;i--) sa[--rs[wv[i]]]=y[i];
swap(x,y);
for(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 n){
int i,j,k=0;
for(int i=1;i<n;i++) rk[sa[i]]=i;
for(int i=1;i<n;height[rk[i++]]=k){
if(k) k--;
for(j=sa[rk[i]-1];r[i+k]==r[j+k];k++);
}
}
char s[Maxn];
int idx[Maxn],f[110];
bool check(int n,int m,int mid,int &cur){
int cnt;
for(int i=1;i<n;i++){
if(height[i]<mid){
f[idx[sa[i]]]=++cur;
cnt=1;
}
else if(f[idx[sa[i]]]!=cur){
f[idx[sa[i]]]=cur;
if(++cnt==m) return true;
}
}
return false;
}
int main()
{
int t,n,m,j,k;
scanf("%d",&t);
while(t--){
n=0;
scanf("%d",&m);
for(int i=0;i<m;i++){
scanf("%s",s+1);
for(j=1;s[j];j++){
r[++n]=s[j];
idx[n]=i;
}
r[++n]=125+2*i;
for(k=j-1;k>=1;k--){
r[++n]=s[k];
idx[n]=i;
}
r[++n]=126+2*i;
}
if(m==1) {printf("%d\n",j-1);continue;}
r[0]=r[++n]=0;
da(n,330);
calheight(n);
memset(f,0,sizeof f);
int l=0,r=n-1,cur=0;
while(l<r){
int mid=l+r+1>>1;
if(check(n,m,mid,cur)) l=mid;
else r=mid-1;
}
printf("%d\n",l);
}
return 0;
}