【代码超详解】HDU 2328 Corporate Identity(KMP)

一、题目描述

在这里插入图片描述

二、算法分析说明与代码编写指导

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");
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值