您的位置:首页 > 大数据 > 人工智能

hdu1867 A + B for you again (KMP)

2013-10-10 20:22 393 查看
http://acm.hdu.edu.cn/showproblem.php?pid=1867


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


题意:

给字符串s1,s2,将两个字符串连接起来,若一个串的前缀是另一个串的后缀,则要覆盖如abcd cdef 连接后为abcdef,再如abcd efab 连接后为efabcd,连接的所有情况中优先考虑其串长度,长度小的优先,其次字典序小的情况优先;

思路 : 两个串以s1s2和s2s1两种情况对接用KMP分别求出其需要覆盖串的长度,根据覆盖长度判断并输出连接后串短的情况,若连接后两种情况长度一样,再判断字典序即可。

#include<stdio.h>
#include<iostream>
#include<string.h>
using namespace std;
const int maxn=100009;
int next[maxn<<1];
char s1[maxn],s2[maxn];
char s[maxn<<1];

int len1,len2;
void getnext()
{
int i=0,j=-1;
next[0]=-1;
while(i<=len1+len2)
{
if(j==-1||s[i]==s[j])next[++i]=++j;
else j=next[j];
}
}
int main()
{
while(scanf("%s%s",s1,s2)!=EOF)
{
len1=strlen(s1);
len2=strlen(s2);
strcpy(s,s2);
s[len2]='A';
s[len2+1]=0;
strcat(s,s1);
getnext();
int j=next[len1+len2+1];
strcpy(s,s1);
s[len1]='A';
s[len1+1]=0;
strcat(s,s2);
getnext();
int k=next[len1+len2+1];
if(k>j)
{
s2[len2-k]=0;
printf("%s%s\n",s2,s1);
continue;
}
if(k<j)
{
s1[len1-j]=0;
printf("%s%s\n",s1,s2);
continue;
}
if(k==j)
{
if(strcmp(s1,s2)<0)
{
s1[len1-j]=0;
printf("%s%s\n",s1,s2);
continue;
}
else
{
s2[len2-k]=0;
printf("%s%s\n",s2,s1);
continue;
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: