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

A + B for you again + KMP

2013-05-12 14:06 183 查看

A + B for you again

Time Limit : 5000/1000ms (Java/Other) Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 49 Accepted Submission(s) : 14
[align=left]Problem Description[/align]
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.

[align=left]Input[/align]
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.

[align=left]Output[/align]
Print the ultimate string by the book.

[align=left]Sample Input[/align]

asdf sdfg
asdf ghjk


[align=left]Sample Output[/align]

asdfg
asdfghjk

[code]#include<iostream>
#include<cstdio>
#include<cstring>

using namespace std;

const int maxn=100010;

int next[maxn];
char s1[maxn],s2[maxn];

void getnext(char *t){
int len=strlen(t);
int i=0,j=-1;
next[0]=-1;
while(i<len){
if(j==-1 || t[i]==t[j]){
i++;j++;
next[i]=j;
}else
j=next[j];
}
}

int KMP(char *s,char *t){
int len1=strlen(s),len2=strlen(t);
int i=0,j=0;
getnext(t);
while(i<len1 && j<len2){
if(j==-1 || s[i]==t[j]){
i++;j++;
}else
j=next[j];
}
if(i==len1)
return j;
return 0;
}

int main(){
while(~scanf("%s%s",s1,s2)){
int x=KMP(s1,s2);
int y=KMP(s2,s1);
if(x==y){
if(strcmp(s1,s2)<0)
printf("%s%s\n",s1,s2+x);
else
printf("%s%s\n",s2,s1+x);
}else if(x>y)
printf("%s%s\n",s1,s2+x);
else
printf("%s%s\n",s2,s1+y);
}
return 0;
}

[/code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: