hdu 1867 A + B for you again
A + B for you again
Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
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和B+A连接之后的字符串的长度,如果长度相同再判断A和B的字典序
1 #include <stdio.h> 2 #include <string.h> 3 4 char s1[100010],s2[100010],s3[200010],s4[200010]; 5 int next_[100010]; 6 void getnext(char s[]) 7 { 8 int i = 0, j = -1; 9 int len = strlen(s); 10 next_[0] = -1; 11 while(i < len) 12 { 13 if (j == -1 || s[i] == s[j]) 14 next_[++ i] = ++ j; 15 else 16 j = next_[j]; 17 } 18 } 19 int kmp(char s1[],char s2[]) 20 { 21 getnext(s2); 22 int i = 0, j = 0; 23 int len = strlen(s1),len1 = strlen(s2); 24 while (i < len && j< len1) 25 { 26 if (j == -1 || s1[i] == s2[j]){ 27 i ++; j++; 28 } 29 else 30 j = next_[j]; 31 } 32 if (i == len) 33 return j; 34 return 0; 35 } 36 int main () 37 { 38 while (~scanf("%s%s",s1,s2)) 39 { 40 int l1 = kmp(s1,s2); // 先求出两种情况重合部分的长短 41 int l2 = kmp(s2,s1); 42 43 if (l1 == l2) // 如果长度相同,判断两个字符串的字典序 44 { 45 if (strcmp(s1,s2)<0) 46 printf("%s%s\n",s1,s2+l2); 47 else 48 printf("%s%s\n",s2,s1+l2); 49 } 50 else if(l1 < l2) 51 printf("%s%s\n",s2,s1+l2); 52 else 53 printf("%s%s\n",s1,s2+l1); 54 } 55 return 0; 56 }