poj 1226(二分+后缀数组)

poj 1226

几本上与这题一样,只不过这里还要把读入的字符串的翻转后的字符串也要连上

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#define ms(i, j) memset(i, j, sizeof i)
#define FN2 "poj1226"
using namespace std;
const int MAXN = 100 + 10;
char s[MAXN];
int mini, t, n, m, a[2*MAXN*MAXN], belong[2*MAXN*MAXN], SA[2*MAXN*MAXN], rk[2*MAXN*MAXN], tp[2*MAXN*MAXN], tax[2*MAXN*MAXN], height[2*MAXN*MAXN];
bool cmp(int *f, int i, int k) {return f[SA[i]]==f[SA[i-1]]&&f[SA[i]+k]==f[SA[i-1]+k];}
void build() {
for (int i=0;i<m;i++) tax[i] = 0;
for (int i=0;i<n;i++) tax[rk[i]=a[i]]++;
for (int i=1;i<m;i++) tax[i] += tax[i-1];
for (int i=n-1;i>=0;i--) SA[--tax[rk[i]]] = i;
int p;
for (int k=1;k<=n;k*=2) {
p = 0;
for (int i=n-k;i<n;i++) tp[p++] = i;
for (int i=0;i<n;i++) if (SA[i]>=k) tp[p++] = SA[i] - k;
for (int i=0;i<m;i++) tax[i] = 0;
for (int i=0;i<n;i++) tax[rk[tp[i]]]++;
for (int i=1;i<m;i++) tax[i] += tax[i-1];
for (int i=n-1;i>=0;i--) SA[--tax[rk[tp[i]]]] = tp[i];
swap(rk, tp), p = 0, rk[SA[0]] = 0;
for (int i=1;i<n;i++) rk[SA[i]] = cmp(tp, i, k) ? p : ++p;
if (++p>=n) break;
m = p;
}
}
void getH() {
int k = 0;
for (int i=0;i<n;i++) {
if (k) k--;
int j = SA[rk[i]-1];
while (a[i+k]==a[j+k]) k++;
height[rk[i]] = k;
}
}
void init() {
n = 0, m = 200, mini = 200000000;
scanf("%d", &t);
for (int i=0;i<t;i++) {
scanf("%s", s);
int l1 = strlen(s);
mini = min(l1, mini);
for (int j=0;j<l1;j++) {
belong[n] = i;
a[n++] = s[j];
}
a[n++] = m++;
for (int j=l1-1;j>=0;j--) {
belong[n] = i;
a[n++] = s[j];
}
a[n++] = m++;
}
a[n-1] = 0;
m += 5;
}
int used[MAXN];
bool check(int x) {
int tot = 0;
ms(used, 0);
for (int i=2;i<n;i++) {
if (height[i]<x) {
ms(used, 0);
tot = 0;
continue;
}
if (!used[belong[SA[i-1]]]) used[belong[SA[i-1]]] = true, ++tot;
if (!used[belong[SA[i]]]) used[belong[SA[i]]] = true, ++tot;
if (tot>=t) return true;
}
return false;
}
void solve() {
build(), getH();
int l = 1, r = mini + 1, ans = 0;
while (l<r) {
int mid = (l+r)/2;
if (check(mid)) {
ans = mid;
l = mid + 1;
} else r = mid;
}
printf("%d\n", ans);
}
int main() {
#ifndef ONLINE_JUDGE
freopen(FN2".in","r",stdin);freopen("1.out","w",stdout);
#endif
int kase; scanf("%d", &kase);
while(kase--) init(), solve();
return 0;
}
------ 本文结束 ------