【题目】
A + B for you again
Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4556 Accepted Submission(s): 1179
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
【题意】求出两个字符串相连去掉合并第一个字符串的后缀与第二个字符串相同的前缀(可以交换顺序),求出合并后最短的字符串,如果一样长,取最短的;
【分析】分别求出两个顺序的next数组,next[n]就是前缀和后缀重叠的长度,比较输出就可以了;
【AC CODE】 31ms
#include <cstdio>
#include <cstring>
#include <cctype>
#include <cmath>
#include <map>
//#include <unordered_map>
#include <queue>
#include <stack>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
typedef long long LL;
#define rep(i,a,n) for(int i = a; i < n; i++)
#define repe(i,a,n) for(int i = a; i <= n; i++)
#define per(i,n,a) for(int i = n; i >= a; i--)
#define clc(a,b) memset(a,b,sizeof(a))
const int INF = 0x3f3f3f3f, MAXN = 100010;
int nxt[MAXN<<1];
void get_next(char *x, int m)
{
int i = 0, j = -1;
nxt[0] = -1;
while(i < m)
{
while(~j && x[i] != x[j]) j = nxt[j];
nxt[++i] = ++j;
}
}
char a[MAXN<<1], b[MAXN], c[MAXN<<1];
int main()
{
#ifdef SHY
freopen("e:\\1.txt", "r", stdin);
#endif
while(~scanf("%s %s", a, b))
{
int lena = strlen(a), lenb = strlen(b);
int n = lena +lenb;
strcpy(c,b);
strcat(c,a);
strcat(a,b);
get_next(a,n);
a[lena] = 0;
int ans = min(min(nxt[n],lenb),lena);
get_next(c,n);
nxt[n] = min(min(lena,nxt[n]), lenb);
if(nxt[n] == ans)
{
strcpy(c,b);
strcat(c,a+nxt[n]);
strcat(a,b+ans);
if(strcmp(a,c) < 0) puts(a);
else puts(c);
}
else
{
if(nxt[n] > ans)
{
strcpy(c,a);
strcat(c,b+nxt[n]);
puts(c);
}
else
{
strcpy(c,b);
strcat(c,a+ans);
puts(c);
}
}
}
return 0;
}