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

1867 A + B for you again

2016-06-05 12:57 267 查看


A + B for you again

Time Limit: 5000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 6098    Accepted Submission(s): 1514


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

 

题目大意:给你两个字符串a和b,求字符串a+b,也就是求a的后缀和b的前缀相等的最长长度咯。看样例就可以懂的!!
思路:用kmp求a和b或者b和a的公共长度

<span style="font-size:18px;">#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<map>
#define LL long long
using namespace std;
const int maxn = 100000+5;
int Next[maxn];
void getNext(string s)
{
Next[0]=-1;
Next[1]=0;
int ls=s.size();
for(int i=2;i<ls;i++){
if(s[i-1]==s[Next[i-1]]) Next[i]=Next[i-1]+1;
else{
int t=Next[i-1];
while(s[i-1]!=s[t]){
t=Next[t];
if(t==-1) break;
}
Next[i]=t+1;
}
}
}
int kmp(string a,string b)
{
getNext(b);
int la=a.size(),i=0;
int lb=b.size(),j=0;
while(i<la && j<lb){
if(j==-1 ||a[i]==b[j]) i++,j++;
else{
while(a[i]!=b[j]){
j=Next[j];
if(j==-1) break;
}
}
if(i==la) return j; //注意这里是判断i是否等于la,因为两个字符串肯定是a结束了才算是匹配完了
}
return -1;
}
int main()
{
cin.sync_with_stdio(false);
string a,b,s;
int la,lb,ans1,len1,ans2,len2;
while(cin>>a>>b){
//getNext(a);
len1=kmp(a,b);
//getNext(b);
len2=kmp(b,a);
la=a.size();
lb=b.size();
//cout<<len1<<' '<<len2<<endl;
if(len1==len2){
if(a<b) s=b,cout<<a;
else s=a,cout<<b;
for(int i=0;i<s.size();i++){
if(len1){
len1--;
continue;
}
cout<<s[i];
}
}
else if(len1>len2){
cout<<a;
for(int i=0;i<lb;i++){
if(len1){
len1--;continue;
}
cout<<b[i];
}
}
else{
cout<<b;
for(int i=0;i<la;i++){
if(len2){
len2--;continue;
}
cout<<a[i];
}
}
cout<<endl;
}
}
</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: