CodeForces - 25E Test (KMP应用)

Description

Sometimes it is hard to prepare tests for programming problems. Now Bob is preparing tests to new problem about strings — input data to his problem is one string. Bob has 3 wrong solutions to this problem. The first gives the wrong answer if the input data contains the substring s1, the second enters an infinite loop if the input data contains the substrings2, and the third requires too much memory if the input data contains the substrings3. Bob wants these solutions to fail single test. What is the minimal length of test, which couldn't be passed by all three Bob's solutions?

Input

There are exactly 3 lines in the input data. The i-th line contains stringsi. All the strings are non-empty, consists of lowercase Latin letters, the length of each string doesn't exceed105.

Output

Output one number — what is minimal length of the string, containing s1, s2 ands3 as substrings.

Sample Input

Input
ab
bc
cd
Output
4
Input
abacaba
abaaba
x
Output
11

题意:将3个字符串连接起来,重复的可以重叠不用计算,输出最短的长度

思路:首先我们可以想到KMP模式匹配,然后就是枚举排列,求出最短的长度

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 100050;

char str[3][maxn];
int next[3][maxn], len[3];

void get_next(int x) {
	int k = -1, j = 0;
	next[x][0] = -1;
	while (j < len[x]) {
		if (k == -1 || str[x][k] == str[x][j]) {
			++k;
			++j;
			next[x][j] = k;
		}
		else k = next[x][k];
	}
}

int kmp(int x, int y) {
	int j = 0, k = 0;
	while (j < len[y] && k < len[x]) {
		if (j == -1 || str[x][k] == str[y][j]) {
			j++, k++;
		}
		else j = next[y][j];
	}
	return j; 
}

int main() {
	while (scanf("%s%s%s", str[0], str[1], str[2]) != EOF) {
		len[0] = strlen(str[0]);
		len[1] = strlen(str[1]);
		len[2] = strlen(str[2]);
		for (int i = 0; i < 3; i++)
			get_next(i);
		int ans = -10;
		for (int i = 0; i < 3; i++)
			for(int j = 0; j < 3; j++) {
				if (i == j) 
					continue;
				for (int k = 0; k < 3; k++) {
					if (k == j || k == i)
						continue;
					int z = kmp(i, j);
					int tmp = z;
					if (len[j] == z)
						tmp += kmp(i, k);
					else tmp += kmp(j, k);
					ans = max(ans, tmp);
				}
			}
		printf("%d\n", (len[0] + len[1] + len[2]) - ans);
	}	
	return 0;
}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值