給n個串,找到一個字符串S。
使得,每個串裏要麼有S,要麼有S的反轉。
首先構造字符串,把每個字符串和其反轉連接在一起(這個中間也要用字符分割!!很重要!!),然後把所有串拼接起來,兩兩之間用一個字符(不會出現在串裏的)分割。
然後二分答案,分段height數組,檢驗。
答案錯誤的同學們試試看
1
2
bcbcb
bcbcb
這個東西。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
using namespace std;
const int nMax = 100001;
char str[nMax+1];
int sa[nMax], rank[nMax], height[nMax];
int wa[nMax], wb[nMax], wv[nMax], wd[nMax];
int cmp(int *r, int a, int b, int l){
return r[a] == r[b] && r[a+l] == r[b+l];
}
void da(char *r, int n, int m){ // 倍增算法 r爲待匹配數組 n爲總長度 m爲字符範圍
int i, j, p, *x = wa, *y = wb, *t;
for(i = 0; i < m; i ++) wd[i] = 0;
for(i = 0; i < n; i ++) wd[x[i]=r[i]] ++;
for(i = 1; i < m; i ++) wd[i] += wd[i-1];
for(i = n-1; i >= 0; i --) sa[-- wd[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 ++) wd[i] = 0;
for(i = 0; i < n; i ++) wd[wv[i]] ++;
for(i = 1; i < m; i ++) wd[i] += wd[i-1];
for(i = n-1; i >= 0; i --) sa[-- wd[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(char *r, int n){ // 求height數組。
int i, j, k = 0;
for(i = 1; i <= n; i ++)
{
rank[sa[i]] = i;
//cout<<sa[i]<<endl;
}
for(i = 0; i < n; height[rank[i ++]] = k){
for(k ? k -- : 0, j = sa[rank[i]-1]; r[i+k] == r[j+k]; k ++);
}
}
int n;
int len[120];
char input[120][120];
bool appear[120];
int find(int sa)
{
if(sa<len[0]-1) return 0;
for(int i=0;i<=n-2;i++)
{
if(sa>=len[i] && sa<len[i+1]-1) return i+1;
}
return 110;
}
bool test(int ans)
{
int seq=0;
for(int j=0;j<n;j++) appear[j]=0;
for(int i=len[n-1]-1;i>=1;i--)
{
if(height[i]<ans)
{
seq=0;
bool ac=true;
for(int j=0;j<n;j++)
{
if(appear[j]==false) ac=false;
}
if(ac==true) return true;
for(int j=0;j<n;j++) appear[j]=0;
}
else
{
if(seq==0)
{
seq+=2;
int ia=find(sa[i]);
int ib=find(sa[i-1]);
appear[ia]=appear[ib]=1;
}
else
{
seq++;
int ib=find(sa[i-1]);
appear[ib]=1;
}
}
}
return false;
}
int main()
{
int t;
cin>>t;
while(t--)
{
cin>>n;
int pt=0;
for(int i=0;i<n;i++)
{
scanf("%s",input[i]);
int now_len=strlen(input[i]);
if(i==0) len[i]=2*now_len+2;
else len[i]=len[i-1]+2*now_len+2;
for(int j=0;j<now_len;j++) str[pt++]=input[i][j];
str[pt++]=(i+2)%10+1;//這邊一定要加一個,否則4個bcbcb出來的結果是10個。。。
for(int j=now_len-1;j>=0;j--) str[pt++]=input[i][j];
if(i==n-1) str[pt++]=0;
else str[pt++]=(i+1)%10+1;
}
da(str,len[n-1],140);
calHeight(str,len[n-1]-1);
int l=1;
int r=100;
int ans=0;
while(l<=r)
{
int mid=(l+r)/2;
if(test(mid)==true)
{
ans=max(ans,mid);
l=mid+1;
}
else r=mid-1;
}
printf("%d\n",ans);
}
return 0;
}