HDU1867 A + B for you again【KMP】
作者:互联网
Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 9765 Accepted Submission(s): 2410
Problem Description
Generally speaking, there are a lot of problems about strings processing. Now you encounter another such problem. If you get two strings, such as “asdf” and “sdfg”, the result of the addition between them is “asdfg”, for “sdf” is the tail substring of “asdf” and the head substring of the “sdfg” . However, the result comes as “asdfghjk”, when you have to add “asdf” and “ghjk” and guarantee the shortest string first, then the minimum lexicographic second, the same rules for other additions.
Input
For each case, there are two strings (the chars selected just form ‘a’ to ‘z’) for you, and each length of theirs won’t exceed 10^5 and won’t be empty.
Output
Print the ultimate string by the book.
Sample Input
asdf sdfg
asdf ghjk
Sample Output
asdfg
asdfghjk
Author
Wang Ye
Source
2008杭电集训队选拔赛——热身赛
问题链接:HDU1867 A + B for you again
问题简述:(略)
问题分析:
给定2个字符串a和b,输出a+b或b+a中长度较短的字符串,若其长度相同则输出字典顺序较小者。其中的+运算定义为:a最长后缀和b最长前缀相等则合并。例如:abcdef+defppp=abcdefppp。
实现方法是使用KMP算法分别计算,一是a后缀和b前缀的最长相同序列(考虑a+b),二是b后缀和a前缀的最长相同序列(考虑b+a)。然后,从中选出较长的序列输出结果,若长度相等则按字典顺序输出结果。
程序说明:(略)
参考链接:(略)
题记:(略)
AC的C语言程序如下:
/* HDU1867 A + B for you again */
#include <stdio.h>
#include <string.h>
#define N 100000
char s1[N + 1], s2[N + 1];
int next[N + 1];
void set_next(char s[], int next[], int len)
{
int i, j;
i = 0, j = next[0] = -1;
while (i < len) {
while (j != -1 && s[i] != s[j])
j = next[j];
next[++i] = ++j;
}
}
int kmp(char *s, char *t)
{
int i = 0, j = 0;
int lens = strlen(s), lent = strlen(t);
set_next(t, next, lent);
while (i < lens && j < lent) {
if (j == -1 || s[i] == t[j])
i++, j++;
else j = next[j];
}
return i == lens ? j : 0;
}
int main(void)
{
while(scanf("%s%s", s1, s2) != EOF) {
int k1 = kmp(s1, s2);
int k2 = kmp(s2, s1);
if(k1 > k2)
printf("%s%s\n", s1, s2 + k1);
else if(k1 < k2)
printf("%s%s\n", s2, s1 + k2);
else {
if(strcmp(s1, s2) < 0)
printf("%s%s\n", s1, s2 + k1);
else
printf("%s%s\n", s2, s1 + k2);
}
}
return 0;
}
标签:again,HDU1867,int,s2,s1,next,k2,KMP,asdf 来源: https://www.cnblogs.com/tigerisland45/p/10353263.html