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>
相关文章推荐
- Main函数的参数
- 人工智能与信号处理--看知乎问答有感.
- Grails里DOMAIN类的一对一,一对多,多对多关系总结及集成测试
- Facebook发布人工智能产品DeepText:能以人类智商
- "Factorial Trailing Zeroes" and "Pascal's Triangle II"
- 第25课:基于MAT分析Shallow Heap和Retained Heap
- 正则表达式--抓取email地址
- 【杭电】[1302]The Snail
- 论文笔记之:Attention For Fine-Grained Categorization
- Mac升级到EI Captain之后pip install 无法使用问题
- 游戏编程中的人工智能-遗传算法入门(五)
- 217. Contains Duplicate
- 1285:Combinations, Once Again
- 【Leetcode】Climbing Stairs
- AIDL简单实现(2)
- AIDL简单实现(1)
- kafka集群启动遇到LeaderNotAvailableException错误
- UVA253——骰子涂色(Cube painting)
- POJ1804 Brainman (逆序对)
- 使用行为树(Behavior Tree)实现游戏AI