一、题目描述
二、算法分析说明与代码编写指导
KMP
从短到长枚举任意一个字符串(这里取第一个)的全部子串,用这个子串去匹配其它字符串。全部匹配成功且字典序更小就记录该子串作为答案。
优化:由于 next 数组是基于模式串 p 生成的。而每一个枚举的子串 p 会用于匹配其它 (n - 1) 个字符串。这时候只需要生成 next 数组 1 次。
三、AC 代码
#include<cstdio>
#include<cstring>
#include<algorithm>
#pragma warning(disable:4996)
using namespace std;
template<class _Nty> inline void getnext(const char* const _Pattern, _Nty* const _Next, const _Nty& _PatternLen) {
_Nty i = 1, j = 0; _Next[1] = 0;
while (i <= _PatternLen) {
if (j == 0 || _Pattern[i] == _Pattern[j]) { ++i, ++j, _Next[i] = j; }
else j = _Next[j];
}
}//The index of the head of _Pattern string is 1.
template<class _Nty, class _Rty = unsigned> inline _Rty KMP(const char* const _Target, const char* const _Pattern, _Nty* const _Next, const _Nty& _TargetLen, const _Nty& _PatternLen) {
_Nty i = 1, j = 1;
//_Next[1] = 0; getnext(_Pattern, _Next, _PatternLen);
while (i <= _TargetLen) {
if (j == 0 || _Target[i] == _Pattern[j]) { ++i, ++j; }
else j = _Next[j];
if (j > _PatternLen) { return 1; }
}
return 0;
}//The index of the head of _Pattern string is 1.
unsigned n, Next[202], L[4000]; char s[4000][203], p[202], r[202]; bool updated, found, ok;
int main() {
for (;;) {
scanf("%u", &n); getchar(); ok = false; if (n == 0)return 0;
for (unsigned i = 0; i < n; ++i) { fgets(s[i] + 1, 202, stdin); L[i] = strlen(s[i] + 1) - 1; }
for (unsigned l = 1; l <= *L; ++l) {
updated = false;
for (unsigned i = 1, im = *L - l + 1; i <= im; ++i) {
copy(s[0] + i, s[0] + i + l, p + 1); found = true; getnext(p, Next, l);
for (unsigned j = 1; j < n; ++j) {
if (KMP(s[j], p, Next, L[j], l) == 0) { found = false; break; }
}
if (found) {
if (!updated) { copy(p + 1, p + 1 + l, r); r[l] = 0; updated = true; ok = true; }
else if (strcmp(p + 1, r) < 0) { copy(p + 1, p + 1 + l, r); r[l] = 0; ok = true; }
}
}
}
if (ok)puts(r);
else puts("IDENTITY LOST");
}
}