题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1867
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
刚学的,自己做的时候没有写明白,后来看了大神的....
代码:
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<string>
#include<math.h>
#include<stdlib.h>
#include<map>
#include<queue>
#define max(x,y)x>y?x:y
#define min(x,y)x<y?x:y
using namespace std;
const int maxn=1000005;
const int maxm=1000005;
char a[maxn],b[maxn];
int next[maxn];
void get_next(char str[])
{
int len=strlen(str);
int i=1,j=0;
next[0]=-1;
while(i<len)
{
if(j==-1||str[i]==str[j])
{
i++;
j++;
next[i]=j;
}
else
j=next[j];
}
}
int kmp(char str1[],char str2[])
{
int len1=strlen(str1);
int len2=strlen(str2);
get_next(str2);
int i=0,j=0;
while(i<len1&&j<len2)
{
if(j==-1||str1[i]==str2[j])
{
i++;
j++;
}
else
j=next[j];
}
if(i==len1)
return j;
return 0;
}
int main()
{
//freopen("in.txt","r",stdin);
while(scanf("%s %s",a,b)!=EOF)
{
int x=kmp(a,b);
int y=kmp(b,a);
if(x==y)
{
if(strcmp(a,b)>0)
{
printf("%s",b);
printf("%s",a+x);
}
else
{
printf("%s",a);
printf("%s",b+x);
}
}
else if(x>y)
{
printf("%s",a);
printf("%s",b+x);
}
else
{
printf("%s",b);
printf("%s",a+y);
}
printf("\n");
}
return 0;
}