hdu1867

来源:互联网 发布:淘宝客转换淘口令软件 编辑:程序博客网 时间:2024/05/21 06:36

A + B for you again

Time Limit: 5000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3789    Accepted Submission(s): 964


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 sdfgasdf ghjk
 

Sample Output
asdfgasdfghjk
 

Author
Wang Ye
 

Source
2008杭电集训队选拔赛——热身赛
 

#include<iostream>#include<cstdio>#include<cstring>using namespace std;const int maxn = 100005;char a[maxn], b[maxn];int next[maxn];void getNext(char c[]){int n = strlen(c);next[0] = -1;int j = -1;for(int i = 1; i < n; i++){while(j!=-1&&c[j+1]!=c[i]){j = next[j];}if(c[j+1]==c[i]){j += 1;}next[i] = j;}}int kmp(char str1[], char str2[]){int j = -1;getNext(str2);int len1 = strlen(str1);int len2 = strlen(str2);for(int i = 0; i < len1; i++){while(j!=-1&&str2[j+1]!=str1[i]){j = next[j];}if(str2[j+1] == str1[i]){j += 1;}if(i==len1-1){break;}if(j==len2-1){j = next[j];}}return j;}int main(){//freopen("in.txt", "r", stdin);while(scanf("%s %s", a, b)!=EOF){int len1, len2;int ele1 = kmp(a, b);int ele2 = kmp(b, a);if(ele1==ele2){if(strcmp(a, b)>0){printf("%s", b);printf("%s\n", a+ele2+1);}else{printf("%s", a);printf("%s\n", b+ele1+1);}}else if(ele1>ele2){printf("%s", a);printf("%s\n", b+ele1+1);}else{printf("%s", b);printf("%s\n", a+ele2+1);}a[0] = '\0';b[0] = '\0';}return 0;}
0 0