HDU 1867 A + 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


分析:题目要求:1、求和字符串最短;2、字典序最小;

由题,串一的最长的后缀匹配串二的最长前缀或整个串二,这两个串可以交换位置;    比如 abc abc = abc  、 aaaa aa =aaaa   、abcd cd = abcd 、abcd cb= abcdcb

用kmp算法求解,分别以串1为模式串、串2为文本串 ;串1 为文本串、串2为模式串;找到两字符的最长匹配。

AC代码:

#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=1e5+10;
char s1[maxn],s2[maxn];
int next[maxn];

void get_next(char* s){
  int len=strlen(s);
  next[0]=0;
  int k=0;
  for(int p=1;p<len;p++){
  	while(k>0 && s[p]!=s[k]){
  		k=next[k-1];
	  }
	  
	  if(s[k]==s[p]) k++;
	  
	  next[p]=k;
  }	
} 

int KMP(char* s1,char *s2){//模式串、文本串 
   get_next(s1);
   int l1=strlen(s1);
   int l2=strlen(s2);
   int i=0,j=0;
   while(i<l1 && j<l2){
   	if(s1[i]==s2[j]) {
   		i++;j++;
	}
	else if(i==0) j++;
	
	else i=next[i-1]; 
   }
   
   if(j==l2&&i==l1 || i<l1)return i;
   return 0;
}

int main(){
	while(scanf("%s%s",s1,s2)==2){
		int la=KMP(s1,s2); //s1做模式串、s2做文本串 
		int lb=KMP(s2,s1);
		
		if(la>lb || (la==lb && strcmp(s2,s1)<0)){
			printf("%s",s2);
			strcpy(s2,s1+la);
			printf("%s\n",s2);
		}
		else {
			printf("%s",s1);
			strcpy(s1,s2+lb);
			printf("%s\n",s1);
		}
	}
	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柏油

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值