1. 程式人生 > >hdu 1867 A + B for you again

hdu 1867 A + B for you again

roc stdio.h 相同 tween them substr bsp sdf des

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 }

hdu 1867 A + B for you again