题目:http://acm.hdu.edu.cn/showproblem.php?pid=1238
题意:给定一些字符串,求这些字符串和它们的倒置字符串的最长公共长度是多长
思路:把第一个字符串每次去掉前一个字符作为模式串,去匹配其他字符串和它们的倒置字符串,取两者之中的较大值,然后取这些结果中的最小值,就是以当前模式串匹配的公共长度。然后去这些公共长度中的最大值即可
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <queue>
#include <map>
#include <vector>
#include <cstring>
#include <cmath>
#include <set>
using namespace std;
const int N = 210;
const int INF = 0x3f3f3f3f;
char s[N][N];
int nt[N];
int n;
void getnt(char *s)
{
int i = 0, j = -1;
nt[0] = -1;
while(s[i])
{
if(j == -1 || s[i] == s[j])
{
i++, j++;
if(s[i] != s[j]) nt[i] = j;
else nt[i] = nt[j];
}
else j = nt[j];
}
}
int kmp(char *s1, char *s2)
{
int i = 0, j = 0;
int res = 0;
while(s1[i])
{
if(j == -1 || s1[i] == s2[j])
i++, j++;
else j = nt[j];
res = max(res, j);
if(j != -1 && !s2[j]) //s1串包含s2串,直接返回j
return j;
}
return res;
}
void solve()
{
int len[N];
int res = 0;
for(int i = 0; i < n; i++)
len[i] = strlen(s[i]);
for(int i = 0; i < len[0]; i++)
{
getnt(s[0] + i);
int tmp = INF;
for(int j = 1; j < n; j++)
{
int tmp1 = kmp(s[j], s[0] + i);
reverse(s[j], s[j] + len[j]);
int tmp2 = kmp(s[j], s[0] + i);
//reverse(s[j], s[j] + len[j]);
tmp = min(tmp, max(tmp1, tmp2));
}
res = max(res, tmp);
}
printf("%d\n", res);
}
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
scanf("%d", &n);
for(int i = 0; i < n; i++)
scanf(" %s", s[i]);
solve();
}
return 0;
}