hdu 1867 A + B for you again【KMP】【判断前后缀】

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

题意:给定两个串,连接两个串的公共前后缀输出,如果没有公共前后缀,按照字典序小的串在前连接输出,不存在包含关系(例如abcd bc 输出abcdbc)

思路:当匹配到了主串的末尾时,直接返回此时模式串的下标,表示最后匹配位置,也就是公共前后缀部分。我们需要尽可能取较多的公共匹配部分,所以,取较大下标。

数据:

输入

abcd   bcd

aaa b

abcd bc

输出

abcd

aaab

abcd bc


#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int maxn = 100010;
#define inf 0x3f3f3f3f
char str1[maxn],str2[maxn];
int next1[maxn],next2[maxn];
int l1,l2;
void get_next(int *next,char s[])
{
	int i,j;
	next[0] = j = -1;
	i = 0;
	while(s[i]!='\0')
	{
		while(j!=-1&&s[i]!=s[j])
			j = next[j];
		next[++i] = ++j;
	}
	return;
}

int KMP(char *s1,char *s2,int length,int *next)
{
	int i,j;
	i = j = 0;
	while(s1[i]!='\0')
	{
		while(j!=-1&&s1[i]!=s2[j])
			j = next[j];
		i++;
		j++;
		if(s1[i]=='\0')
			return j;
			
	}
	return 0;
}

int main()
{
	int dis1,dis2;
//	freopen("in.txt","r",stdin);
	while(scanf("%s%s",str1,str2)!=EOF)
	{
		memset(next1,0,sizeof(next1));
		memset(next2,0,sizeof(next2));
		l1 = strlen(str1);
		l2 = strlen(str2);
		get_next(next1,str1);
		get_next(next2,str2);
		dis1 = KMP(str1,str2,l2,next2);
		dis2 = KMP(str2,str1,l1,next1);
		if(dis1 > dis2||(dis1==dis2&&strcmp(str1,str2)<0))
		{
			printf("%s%s\n",str1,str2+dis1);
		}
		else if(dis1 < dis2||(dis1==dis2&&strcmp(str1,str2)>=0))
			printf("%s%s\n",str2,str1+dis2);
	}
	return 0;
}


阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页