最长公共子串(后缀数组解法)
仅正序
poj 2774 long long message
将字符串用不同的分隔符连接起来,求后缀数组和height数组即可,具体需要好好理解sa和height数组的含义。
正序逆序均可
poj 1226 Substrings
将字符串用分隔符与自己的逆序连接后,将所有串连接在一起,然后与正序相同的求法。
第二种情况的代码
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAX = 20010;
int s[MAX],t;
char ss[MAX];
int n,k,size,pos[MAX],sp,vis[110];
int sa[MAX],rank[MAX],height[MAX];
int wa[MAX],wb[MAX],wv[MAX],ws[MAX];
int cmp(int *r,int a,int b,int l) {
return r[a] == r[b] && r[a+l] == r[b+l];
}
void fun(int *r, int n, int m){
int i,j,p,*x = wa, *y = wb, *t;
for(i = 0; i < m; i ++) ws[i] = 0;
for(i = 0; i < n; i ++) ws[x[i] = r[i]] ++;
for(i = 1; i < m; i ++) ws[i] += ws[i-1];
for(i = n-1; i >= 0; i --) sa[--ws[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 ++) ws[i] = 0;
for(i = 0; i < n; i ++) ws[wv[i]] ++;
for(i = 1; i < m; i ++) ws[i] += ws[i-1];
for(i = n-1; i >= 0; i--) sa[--ws[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(int i=1; i<=n; i++)
rank[sa[i]] = i;
for(int i=0; i<n; i++){
if(k) k--;
int j = sa[rank[i]-1];
while(r[i+k] == r[j+k]) k++;
height[rank[i]] = k;
}
}
bool isgood(){
for(int i=1; i<=size-3; i+=2){
vis[i] += vis[i+1];
if(!vis[i]) return false;
}
return true;
}
bool check(int mid){
memset(vis, 0, sizeof(vis));
int cnt = 0;
for(int i=2; i<=k; i++){
if(height[i] >=mid){
if(!vis[pos[sa[i-1]]]){
vis[pos[sa[i-1]]] = 1;
cnt++;
}
if(!vis[pos[sa[i]]]){
vis[pos[sa[i]]] = 1;
cnt++;
}
if(cnt == n) return true;
}
else{
cnt = 0;
memset(vis, 0, sizeof(vis));
}
}
return false;
}
int main(){
int cas;
scanf("%d",&cas);
while(cas--){
t = 1000;
scanf("%d",&n);
k = 0, size = 0,sp = 240;
for(int i=0; i<n; i++){
scanf("%s",ss);
int len = strlen(ss);
t = min(len, t);
for(int j=0; ss[j]; j++){
pos[k] = i;
s[k++] = ss[j];
}
pos[k] = sp;
s[k++] = sp++;
for(int j=len-1; j>=0; j--){
pos[k] = i;
s[k++] = ss[j];
}
pos[k] = sp;
s[k++] = sp++;
}
s[k] = 0;
fun(s, k+1, sp);
calheight(s, k);
int l = 0, r = t, ans = -1;
while(l <= r){
int mid = (l + r) >> 1;
if(check(mid)){
ans = mid;
l = mid + 1;
}
else
r = mid - 1;
}
printf("%d\n",ans);
}
return 0;
}