A + B for you again
Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 7891 Accepted Submission(s): 1984
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
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1867
题目大意:
给出两个字符串合并出一个长度与字典序最小的字符串,且给出的两个串分别为这个合并字符串的前缀与后缀。
题目分析:
注意是先按照长度最小,然后再按照字典序最小输出。
注意题目要求的是最短的字符串能包含所给的两个字符串,这里的包含一定是前一部分或后一部分包含,不能中间包含。
代码:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <string>
#include <queue>
#include <vector>
#include <map>
using namespace std;
typedef long long LL;
const int N=100000+999;
int nex[N];
char s1[N],s2[N];
void make_next(int n,char *a)
{
int i,j;
nex[0]=0;
for(i=1,j=0; i<n ; i++)
{
while(j>0&&a[i]!=a[j])
j=nex[j-1];
if(a[i]==a[j])
j++;
nex[i]=j;
}
}
int KMP(int n,int m,char *a,char *b)
{
make_next(m,b);
int i,j;
for(i=0,j=0; i<n; i++)
{
while(j>0&&a[i]!=b[j])
j=nex[j-1];
if(a[i]==b[j])
j++;
if(j==m)
break;
}
if((i==n-1&&j==m)||i==n) //只能是模式串匹配到主串结束
return j;
return 0;
}
int main()
{
while(scanf(" %s %s",s1,s2)!=EOF)
{
int len1=strlen(s1);
int len2=strlen(s2);
int b=KMP(len1,len2,s1,s2);
int a=KMP(len2,len1,s2,s1);
if(b>a) //s2的前缀与s1的后缀匹配较长
{
printf("%s%s\n",s1,s2+b);
}
else if(a>b)//s1的前缀与s2的后缀匹配较长
{
printf("%s%s\n",s2,s1+a);
}
else //如果匹配长度相等则看字典序从小到大
{
if(strcmp(s1,s2)<0) printf("%s%s\n",s1,s2+b);
else printf("%s%s\n",s2,s1+a);
}
}
return 0;
}