题意:

  给n个字符串,求出最长的子串。使得子串在每个字符串中不重叠地至少出现2次。输出子串长度。

题解:

  用后缀数组求出height数组,之后二分答案。check时对height数组进行分组,并维护每个字符串的最前和最后位置。

#include <bits/stdc++.h>
using namespace std;
const int N = 1e5+;
int t, n, k, len;
int vis[N], val[][];
char s[N];
int r[N];
int sa[N], t1[N], t2[N], c[N], height[N], rank[N];
void SA(int *r, int n, int m) {
int *x = t1, *y = t2;
for(int i = ; i < m; i++) c[i] = ;
for(int i = ; i < n; i++) c[x[i] = r[i]]++;
for(int i = ; i < m; i++) c[i] += c[i-];
for(int i = n-; i >= ; i--) sa[--c[x[i]]] = i;
for(int k = ; k <= n; k <<= ) {
int p = ;
for(int i = n-k; i < n; i++) y[p++] = i;
for(int i = ; i < n; i++) if(sa[i] >= k) y[p++] = sa[i]-k;
for(int i = ; i < m; i++) c[i] = ;
for(int i = ; i < n; i++) c[x[y[i]]]++;
for(int i = ; i < m; i++) c[i] += c[i-];
for(int i = n-; i >= ; i--) sa[--c[x[y[i]]]] = y[i];
swap(x, y);
p = ; x[sa[]] = ;
for(int i = ; i < n; i++)
x[sa[i]] = y[sa[i-]] == y[sa[i]] && y[sa[i-]+k] == y[sa[i]+k] ? p- : p++;
if(p >= n) break;
m = p;
}
int k = , j;
for(int i = ; i < n; i++) rank[sa[i]] = i;
for(int i = ; i < n; height[rank[i++]] = k)
for(k ? k--:, j = sa[rank[i]-]; r[i+k] == r[j+k]; k++);
}
int add(int x, int v) {
int p = vis[sa[x]], c = ;
if(val[p][] == - && val[p][] == -) {
val[p][] = val[p][] = sa[x];
c++;
}
else {
if(sa[x] < val[p][]) {
if(val[p][] - val[p][] < v && val[p][] - sa[x] >= v) c++;
val[p][] = sa[x];
}
else if(sa[x] > val[p][]) {
if(val[p][] - val[p][] < v && sa[x] - val[p][] >= v) c++;
val[p][] = sa[x];
}
}
return c;
}
bool check(int x) {
int cnt = ;
int l = n;
while(l < len) {
if(height[l] < x) {
memset(val, -, sizeof(val));
cnt = ;
cnt += add(l, x);
}
else cnt += add(l, x);
l++;
if(cnt == *n) return true;
}
return false;
}
int main() {
scanf("%d", &t);
while(t--) {
len = ;
scanf("%d", &n);
memset(vis, , sizeof(vis));
for(int i = ; i <= n; i++) {
scanf("%s", s);
k = strlen(s);
for(int j = ; j < k; j++) r[len++] = s[j]-'a'+;
vis[len] = ;
r[len++] = i;
}
for(int i = ; i < len; i++) vis[i] += vis[i-];
SA(r, len, );
int l = , r = 1e5;
while(l <= r) {
int mid = l+r>>;
if(check(mid)) l = mid+;
else r = mid-;
}
printf("%d\n", r);
}
}
05-17 18:30