题目在:http://poj.org/problem?id=1226
不知道为什么当时没有AC掉这个题目,后来看看自己当时提交的代码还是有很多问题的,所以还是写了这个东东,算是自己对这个题目的反思吧。
题目大意:
给出一些字符串的集合 D,然后找出一个字符串S,这个字符串满足如下条件:
S自身,或者S的Reverse,都是D中任意字符串的字串。
求出最长的S的长度。
Sample Input:
2 3 ABCD BCDFF BRCD 2 rose orchid
Sample Output:
2
2
对于第一组数据而言,我们找到的这个字串实际上是CD,所以长度是2
对于第二组数据而言,我们找到的是ro,所以长度是2
分析:
很明显的是,这个字串S也要满足D中,长度最短的那个字符串。 如果要是枚举的话,我们可以从那个最短的入手,因为这样的话,实际枚举的次数是最少的。
例如这最短串是 S0, 我们可以枚举S0的所有后缀Ki( i = 0... Len - 1) ,然后用后缀去匹配D中的其他字符串。
对于每个后缀Ki, 于Sj(j = 1, .... n) 比较的最大匹配长度是 ( m1, m2, ... , mn) 然后我们取得这个最小的,Ki对于字典D的最长匹配字串了。
另外需要说明一点的是,因为我们枚举了所有的后缀Ki,但是KMP工作是从前向后匹配,匹配最大前缀,所以这样的话,也就是枚举出了S0的所有字串。
例如S0为 abc
那么后缀是 abc, bc, c,
然后在KMP的时候在前缀 abc中,会从最短的前缀匹配,一直到可能的最长前缀。a, ab, abc
这样所以的字串就都枚举出来了。
不过这个题目还有一处是说,这个字串S的逆是 Sj的字串也是可以的。
这里我们对Ki做检测的时候,目的是为了找到最长的匹配前缀,如果将Ki取逆,最后的结果就不对了。
这里我们对Sj求逆,其实对整个过程没有什么影响,代码如下:
Source Code
Problem: 1226 User: hopeztm
Memory: 176K Time: 16MS
Language: C++ Result: Accepted
Source Code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
using namespace std;
struct String
{
int strLen;
char str[105];
};
String strAll[105];
int nStrings;
int next[105];
int nextReverse[105];
int cmp(const void* pA, const void *pB)
{
String *a = (String*)pA;
String *b = (String*)pB;
if(a->strLen >b->strLen)
{
return 1;
}
return 0;
}
void GetNext(char str[], int next[])
{
int i,j;
i = 0;
j = -1;
next[0] = -1;
int len = strlen(str);
while(i < len )
{
if(j == -1 || str[i] == str[j])
{
i++;
j++;
next[i] = j;
}
else
{
j = next[j];
}
}
}
int kmpCompare(char strDest[], char strPatter[], int next[]) //求最长前缀匹配长度的 KMP
{
int i,j;
i = 0; //dest string;
j = 0; //pattern string
int maxLen = 0;
int lenDst = strlen(strDest);
int lenPat = strlen(strPatter);
while( i < lenDst)
{
if(j == -1 || strPatter[j]== strDest[i])
{
i++;
j++;
}
else
{
j = next[j];
}
if( j > maxLen)
{
maxLen = j;
}
if( j == lenPat)
{
break;
}
}
return maxLen;
}
void reverseString(const char *pSRC, char *pDst)
{
int len = strlen(pSRC);
int i = 0;
while( i < len)
{
pDst[i] = pSRC[len-i-1];
i++;
}
pDst[len] = '\0';
}
void GetLongestSubString()
{
char strTest[105];
char strReverse[105];
int i,j;
int maxLen = 0;
int matchedLen;
for( i = 0; i < strAll[0].strLen; i++)
{
if(strAll[0].strLen - i < maxLen)
{
break;
}
memcpy(strTest, strAll[0].str + i, sizeof(strAll[0].str) - i * sizeof(char));
GetNext(strTest, next);
int matchedMin = 100000000;
for( j = 1; j < nStrings; j++)
{
reverseString(strAll[j].str, strReverse);
matchedLen = max(kmpCompare(strAll[j].str, strTest, next),
kmpCompare(strReverse, strTest, next));
matchedMin = min(matchedMin, matchedLen);
}
maxLen = max(matchedMin, maxLen);
}
printf("%d\n", maxLen);
}
int main()
{
int nCase;
scanf("%d", &nCase);
while(nCase--)
{
scanf("%d", &nStrings);
for(int i = 0;i < nStrings; i++)
{
scanf("%s", strAll[i].str);
strAll[i].strLen = strlen(strAll[i].str);
}
if(nStrings == 1)
{
printf("%d\n",strAll[0].strLen);
}
else
{
qsort(strAll, nStrings, sizeof(strAll[0]), cmp);
GetLongestSubString();
}
}
return 0;
}