首先二分长度x,将不小于x的height分组。
然后判断连续的一组内,每个后缀所属的每个字符串的个数是否超过一半即可。
二分的时候可以顺便把答案记录下来。
注意每次分组完毕后要给vis清零。
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 110005, maxd = 105, M = 150;
int sa[maxn], rank[maxn], height[maxn];
int wa[maxn], wb[maxn], wv[maxn], cnt[maxn];
void SA(int *r, int n, int m) {
int *x = wa, *y = wb;
for(int i = 0; i < m; i++) cnt[i] = 0;
for(int i = 0; i < n; i++) cnt[x[i] = r[i]]++;
for(int i = 1; i < m; i++) cnt[i] += cnt[i - 1];
for(int i = n - 1; i >= 0; i--) sa[--cnt[x[i]]] = i;
for(int j = 1; j < n; j <<= 1) {
int p = 0;
for(int i = n - j; i < n; i++) y[p++] = i;
for(int i = 0; i < n; i++) if(sa[i] >= j) y[p++] = sa[i] - j;
for(int i = 0; i < n; i++) wv[i] = x[y[i]];
for(int i = 0; i < m; i++) cnt[i] = 0;
for(int i = 0; i < n; i++) cnt[wv[i]]++;
for(int i = 1; i < m; i++) cnt[i] += cnt[i - 1];
for(int i = n - 1; i >= 0; i--) sa[--cnt[wv[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]] && y[sa[i - 1] + j] == y[sa[i] + j] ? p - 1 : p++;
if(p >= n) break;
m = p;
}
}
void calcHeight(int *r, int n) {
int i, j, k;
for(i = j = k = 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, s[maxn], pos[maxd], ans[maxn];
char str[maxn];
bool vis[maxd];
bool check(int x, int len, int k) {
for(int i = 0; i < maxd; i++) vis[i] = 0;
int size = 0, tot = 0;
for(int i = 1; i <= len; i++) {
if(height[i] >= x) {
for(int j = 1; j <= n; j++) {
if(pos[j - 1] < sa[i] && sa[i] < pos[j]) tot += !vis[j], vis[j] = 1;
if(pos[j - 1] < sa[i - 1] && sa[i - 1] < pos[j]) tot += !vis[j], vis[j] = 1;
}
} else {
if(tot > k) ans[++size] = sa[i - 1];
tot = 0;
for(int j = 0; j < maxd; j++) vis[j] = 0;
}
}
if(tot > k) ans[++size] = sa[len];
if(size) return ans[0] = size;
return 0;
}
int main() {
while(1) {
scanf("%d", &n);
if(n == 0) break;
int len = 0, end = 0;
for(int i = 0; i < n; i++) {
scanf("%s", str + len);
for(; str[len] != '\0'; len++) s[len] = str[len] - 'a' + 100;
s[len] = ++end;
pos[i + 1] = len++;
}
s[--len] = 0;
SA(s, len + 1, M);
for(int i = 0; i <= len; i++) rank[sa[i]] = i;
calcHeight(s, len);
int l = 1, r = len + 1, k = n >> 1;
while(l <= r) {
int mid = l + r >> 1;
if(check(mid, len + 1, k)) l = mid + 1;
else r = mid - 1;
}
if(l == 1) printf("?\n");
else
for(int i = 1; i <= ans[0]; i++) {
for(int j = ans[i]; j < ans[i] + l - 1; j++)
printf("%c", str[j]);
printf("\n");
}
printf("\n");
}
return 0;
}