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

49 篇文章 0 订阅
7 篇文章 0 订阅

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的前缀,或者b的后缀加上a的前缀,使得到的字符串最短。A+B或 B+A,千万少算了。

思路:

      KMP模板,然后先把b串当模式串与a串比较得到 j 的的位置x,再把a串当模式串与b串比较得到 j 的位置y,如果x = y,说明到j的位置相等,然后比较a,b的长度,谁短先输出谁;如果x > y,先输出a串,再输出相应 j 位置后的b串;如果x < y,先输出 b 串,在输出相应位置 j 后的a串。

    一开始忘了限制返回  j 的条件,所以WA了一次。

代码:

#include<stdio.h>
#include<string.h>
char a[1000010],b[1000010];
int next[100010];
int len1,len2,len;
void get_next(char str[])
{
	int i,j;
	i=1;
	j=0;
	len=strlen(str);
	while(i<len)
	{
		if(j==0&&str[i]!=str[j])
		{
			next[i]=0;
			i++;
		}
		else if(j>0&&str[i]!=str[j])
		{
			j=next[j-1];
		}
		else
		{
			next[i]=j+1;
			i++;
			j++;
		}
	}
}
int kmp(char str1[],char str2[])
{
	int i,j;
	get_next(str2);
	i=0;
	j=0;
	len1=strlen(str1);
	len2=strlen(str2);
	while(i<len1&&j<len2)
	{
		if(j==0&&str2[j]!=str1[i])
		{
			i++;
		}
		else if(j>0&&str2[j]!=str1[i])
		{
			j=next[j-1];
		}
		else
		{
			i++;
			j++;
		}
	}
	if(i>=len1)
		return j;
	return 0;
}
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",b);
				printf("%s",a+x);
			}
			else
			{
				printf("%s",a);
				printf("%s",b+x);
			}
		}
		else if(x>y)
		{
			printf("%s",a);
			printf("%s",b+x);
		}
		else
		{
			printf("%s",b);
			printf("%s",a+y);
		}
		printf("\n");
		memset(a,0,sizeof(a));
		memset(b,0,sizeof(b));
	}
	return 0;
 } 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值