HDU-1867A + B for you again(kmp)

                                               A + B for you again
 

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

题意描述:

把两个字符串合并,规则是如果一个串的后缀与另一个串的前缀相同则相同部分只输出一次,a串当子串,b串当子串各比较一次,如果两个得到的前后缀合并后长度一样,则按字典顺序输出

程序代码:

#include<stdio.h>
#include<string.h>
void get_next(char *s);
int kmp(char *s1,char *s2);
int next[100010];
char a[100010],b[100010];
int main()
{
	int x,y;
	while(scanf("%s%s",a,b)!=EOF)
	{
		x=kmp(a,b);
		y=kmp(b,a);
		if(x==y)
		{
			if(strcmp(a,b)<0)
				printf("%s%s\n",a,b+x);
			else
				printf("%s%s\n",b,a+x);
		}
		else if(x>y)
			printf("%s%s\n",a,b+x);
		else
			printf("%s%s\n",b,a+y);
	}
	return 0;
}
void get_next(char *s)
{
	int i,j,lens;
	i=1;j=0;next[0]=0;
	lens=strlen(s);
	while(i<lens)
	{
		if(j==0&&s[i]!=s[j])
		{
			next[i]=0;
			i++;
		}
		else if(j>0&&s[i]!=s[j])
			j=next[j-1];
		else
		{
			next[i]=j+1;
			i++;
			j++;
		}
	}
}	
int kmp(char *s1,char *s2)
{
	int i,j,lens1;
	get_next(s2);
	i=0;j=0;
	lens1=strlen(s1);
	while(i<lens1)
	{
		if(j==0&&s1[i]!=s2[j])
			i++;
		else if(j>0&&s1[i]!=s2[j])
			j=next[j-1];
		else 
		{
			i++;
			j++;
		}
	}
	return j;
}

猜你喜欢

转载自blog.csdn.net/hezhiying_/article/details/81163591