【题解】HDU-1238 Substrings

Substrings(HDU-1238)

题面

You are given a number of case-sensitive strings of alphabetic characters, find the largest string X, such that either X, or its inverse can be found as a substring of any of the given strings.

输入

The first line of the input file contains a single integer t (1 <= t <= 10), the number of test cases, followed by the input data for each test case. The first line of each test case contains a single integer n (1 <= n <= 100), the number of given strings, followed by n lines, each representing one string of minimum length 1 and maximum length 100. There is no extra white space before and after a string.

输出

There should be one line per test case containing the length of the largest string found.

样例输入

1
2
3
4
5
6
7
8
2
3
ABCD
BCDFF
BRCD
2
rose
orchid

样例输出

1
2
2
2

提示

思路

枚举子串,暴力KMP即可。

代码

查看代码
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
char s[105][mxn], t[mxn], t2[mxn];
int nxt[mxn], nxt2[mxn], len[mxn];

void getnxt(char* t, int m)
{
int i = 0, j = -1; nxt[0] = -1;
while (i < m)
{
if (j == -1 || t[i] == t[j]) {
i++, j++;
// if (t[i] == t[j])
// nxt[i] = nxt[j]; // next数组优化
// else
nxt[i] = j;
} else
j = nxt[j];
}
}

int KMP(char* s, char* t, int n, int m)
{
int i = 0, j = 0, ans = 0;
while (i < n)
{
if (j == -1 || s[i] == t[j]) {
i++, j++;
if (j >= m) { // 匹配
// ans++;
// j = nxt[j];
return i-j;
}
} else
j = nxt[j];
}
// return ans;
return -1;
}

int main()
{
int T; scanf("%d", &T);
while(T--)
{
int n; scanf("%d", &n);
for(int i=0; i<n; i++){
scanf("%s", s[i]);
len[i] = strlen(s[i]);
}
int ans=0;
for(int i=0; i<len[0]; i++) // 枚举模式串起点
{
int tl = 0, k;
for(int j=i; j<len[0]; j++) // 枚举模式串长度
{
t[tl++] = s[0][j];
for(int x=0; x<tl; x++) t2[x] = t[tl-x-1];
t[tl] = t2[tl] = '\0';
getnxt(t, tl);
getnxt(t2, tl);
for(k=0; k<n; k++) // 枚举所有文本串
if(KMP(s[k], t, len[k], tl) == -1 && KMP(s[k], t2, len[k], tl) == -1)
break;
if(k>=n) // 满足条件
ans = max(ans, tl);
}
}
printf("%d\n", ans);
}
return 0;
}
_/_/_/_/_/ EOF _/_/_/_/_/