A + B for you again
Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 9291 Accepted Submission(s): 2274
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
简单的应用kmp以及next数组。。
1 #include <cstdio> 2 #include <iostream> 3 #include <string.h> 4 #include <string> 5 #include <map> 6 #include <queue> 7 #include <deque> 8 #include <vector> 9 #include <set> 10 #include <algorithm> 11 #include <math.h> 12 #include <cmath> 13 #include <stack> 14 #include <iomanip> 15 #define mem0(s1) memset(s1,0,sizeof(s1)) 16 #define meminf(s1) memset(s1,0x3f,sizeof(s1)) 17 #define ll long long 18 using namespace std; 19 int nex[1000005],l1,l2; 20 void getn(int n,char c[]) 21 { 22 int i=0,j=-1; 23 nex[0]=-1; 24 while(i<n) 25 { 26 if(j==-1||c[i]==c[j]) 27 { 28 i++;j++;nex[i]=j; 29 } 30 else j=nex[j]; 31 } 32 return; 33 } 34 int kmp(char s1[],char s2[]) 35 { 36 int i,j=0,n,m; 37 n=strlen(s1); 38 m=strlen(s2); 39 getn(m,s2); 40 for(i=0;i<n;i++) 41 { 42 while(j&&s1[i]!=s2[j])j=nex[j]; 43 if(s1[i]==s2[j])j++; 44 } 45 return j; 46 } 47 int main() 48 { 49 char s1[100005],s2[100005]; 50 wshile(~scanf("%s%s",s1,s2)) 51 { 52 l1=strlen(s1);l2=strlen(s2); 53 int h=kmp(s1,s2); 54 int hh=kmp(s2,s1); 55 if(h>hh||(h==hh&&strcmp(s1,s2)<0)) printf("%s%s ",s1,s2+h); 56 else printf("%s%s ",s2,s1+hh); 57 } 58 return 0; 59 }