HDU 1867 A + B for you again

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

题目大意:

两个串,放在一起,若一个串的前缀和另一个串的后缀相同,那么就可以重叠,先后顺序可以随意。 输出放在一起后最短的串,如果长度相同就输出字典序最小的串。

解题思路:kmp模板题,找到公共前后缀的最大长度。

代码:

#include <stdio.h>
#include <string.h>
int next[100010];
char s[100010],p[100010];
char s0[100010],s1[100010];
void getnext(char p[])
{
	int j=0;
	int k=-1;
	next[0]=-1;
	int lp=strlen(p);
	while(j<lp)
	{
		if(k==-1||p[j]==p[k])//p[k]表示前缀,p[j]表示后缀 
		{
			j++;
			k++;
			next[j]=k;
		}
		else
			k=next[k];	
	}
}

int kmp(char s[],char p[])
{
	getnext(p);
	int i=0;
	int j=0;
	int ls=strlen(s);
	int lp=strlen(p);
	while(i<ls)
	{
		if(j==-1||s[i]==p[j])
		{
			i++;
			j++;
		}
		else
			j=next[j];
	}
	return j;//返回的是匹配的最大长度 
}

int main()
{
	int i,k1,k2;
	while(scanf("%s%s",s,p)!=EOF)
	{
		k1=kmp(s,p);
		k2=kmp(p,s);
		//printf("k1-----%d\nk2-----%d\n",k1,k2);
		if(k1>k2)
			printf("%s%s\n",s,p+k1);//字符串p加一个数字k表示从p串开始地址的k位输出
		else if(k1<k2)
			printf("%s%s\n",p,s+k2);
		else{//k1==k2,输出字典序小的 
			strcpy(s0,s);
			strcat(s0,p+k1);
			strcpy(s1,p);
			strcat(s1,s+k1);
			if(strcmp(s0,s1)>0)
				printf("%s\n",s1);
			else
				printf("%s\n",s0);
		}
	} 
	return 0; 
}

猜你喜欢

转载自blog.csdn.net/hello_cmy/article/details/81193150
今日推荐