hdu A + B for you again

A + B for you again

Time Limit : 5000/1000ms (Java/Other)   Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 3   Accepted Submission(s) : 1
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的应用
代码
View Code
 1 #include <iostream>
2 #include <cstring>
3 #include <cstdio>
4 using namespace std;
5 const int Max=100010;
6 int next[Max];
7 char str1[Max],str2[Max];
8 void get_next(char *pat,int len)
9 {
10 int i=0,j=-1;
11 next[0]=-1;
12 while(i<=len)
13 {
14 if(j==-1||pat[i]==pat[j])
15 {
16 i++,j++;
17 next[i]=j;
18 }
19 else
20 j=next[j];
21 }
22 }
23
24 int kmp(char *s,char *pat)
25 {
26 int i = 0,j = 0,len1 = strlen(s),len2 = strlen(pat);
27 get_next(pat,len2);
28 while(i<len1&&j<len2)
29 {
30 if( j == -1 || s[i] == pat[j])
31 {
32 ++i;
33 ++j;
34 }
35 else j = next[j];
36 }
37 if(i>=len1)
38 return j;
39 else
40 return 0;
41 }
42 int main()
43 {
44 while(scanf("%s%s",str1,str2)!=EOF)
45 {
46 int idx1,idx2;
47 idx2 = kmp(str1,str2);
48 idx1 = kmp(str2,str1);
49 // printf("idx2=%d idx1=%d\n",idx2,idx1);
50 if( idx1 == idx2)
51 {
52 if(strcmp(str1,str2) < 0)
53 {
54 printf("%s%s",str1,str2+idx2);
55 }
56 else
57 {
58 printf("%s%s",str2,str1+idx1);
59 }
60 }
61 else if( idx2 > idx1 )
62 {
63 printf("%s%s",str1,str2+idx2);
64 }
65 else
66 {
67 printf("%s%s",str2,str1+idx1);
68 }
69 printf("\n");
70 }
71 return 0;
72 }


posted on 2011-11-06 19:51  Goal  阅读(383)  评论(0编辑  收藏  举报

导航