hdu1867 A + B for you again [kmp模板]

A + B for you again

hdu1867 题目链接

Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 9031 Accepted Submission(s): 2184

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

解题思路

题目大概就是说两个串,放在一起,如过一个串的前缀和另一个串的后缀相同,那么就可以重叠,先后顺序可以随意。
输出放在一起后最短的串,如果长度相同就输出字典序最小的串。
大概就是一个kmp模板题,找到公共前后缀的最大长度。

程序代码

#include <stdio.h>
#include <string.h>
int next[100010];
char p[100010];
char s[100010];
char s0[200010];
char s1[200010];

void get_next(char p[]){
	int j=0;
	int k=-1;
	int l=strlen(p);
	next[0]=-1;
	while(j<l){
		if(p[j]==p[k]||k==-1){
			j++;
			k++;
			next[j]=k;
		}
		else
			k=next[k];
	}
	return ;
}
int kmp(char s[],char p[]){
	memset(next,0,sizeof(next));
	get_next(p);
	int i=0;
	int j=0;
	int l1=strlen(s);
	int l2=strlen(p);
	while(i<l1){
		if(p[j]==s[i]||j==-1){
			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);
		if(k1>k2){
			printf("%s%s\n",s,p+k1);
		}
		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); 
		}
		memset(s,0,sizeof(s));
		memset(p,0,sizeof(p));
		memset(s0,0,sizeof(s0));
		memset(s1,0,sizeof(s1));
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值