Given two strings, if the prefix of one string is the suffix of another string, it can be merged. It is required that the merged strings be as short as possible, and then the strings should be as short as possible in the lexicographically;
Idea: two strings can be combined in different order. For each combination, the next array of the kmp algorithm is obtained. next [len] is the length of the two strings that can be merged;
[Cpp]
# Include <iostream>
# Include <stdio. h>
# Include <string. h>
# Include <stdlib. h>
# Define min (a, B) a <B? A: B
Using namespace std;
Char s [200005], a [100005], B [100005];
Int next [200005];
Int KMP (int len, int n)
{
Int I = 0, j =-1;
Next [0] =-1;
While (I <n ){
If (j =-1 | s [I] = s [j]) {
I ++;
J ++;
Next [I] = j;
}
Else
J = next [j];
}
While (next [n]> len ){
N = next [n];
}
Return next [n];
}
Int main ()
{
While (scanf ("% s", a, B )! = EOF ){
Int len1 = strlen ();
Int len2 = strlen (B );
Strcat (strcpy (s, a), B );
Int ans1 = KMP (min (len1, len2), len1 + len2); // The first parameter is the maximum length that can be merged.
Strcat (strcpy (s, B), );
Int ans2 = KMP (min (len1, len2), len1 + len2 );
Int I;
If (ans1> ans2 ){
For (I = 0; I <len2; I ++) printf ("% c", B [I]);
For (I = ans1; I <len1; I ++) printf ("% c", a [I]);
}
Else if (ans2> ans1 ){
For (I = 0; I <len1; I ++) printf ("% c", a [I]);
For (I = ans2; I <len2; I ++) printf ("% c", B [I]);
}
Else {
If (strcmp (a, B)> 0 ){
For (I = 0; I <len2; I ++) printf ("% c", B [I]);
For (I = ans1; I <len1; I ++) printf ("% c", a [I]);
}
Else {
For (I = 0; I <len1; I ++) printf ("% c", a [I]);
For (I = ans2; I <len2; I ++) printf ("% c", B [I]);
}
}
Printf ("\ n ");
}
Return 0;
}
# Include <iostream>
# Include <stdio. h>
# Include <string. h>
# Include <stdlib. h>
# Define min (a, B) a <B? A: B
Using namespace std;
Char s [200005], a [100005], B [100005];
Int next [200005];
Int KMP (int len, int n)
{
Int I = 0, j =-1;
Next [0] =-1;
While (I <n ){
If (j =-1 | s [I] = s [j]) {
I ++;
J ++;
Next [I] = j;
}
Else
J = next [j];
}
While (next [n]> len ){
N = next [n];
}
Return next [n];
}
Int main ()
{
While (scanf ("% s", a, B )! = EOF ){
Int len1 = strlen ();
Int len2 = strlen (B );
Strcat (strcpy (s, a), B );
Int ans1 = KMP (min (len1, len2), len1 + len2); // The first parameter is the maximum length that can be merged.
Strcat (strcpy (s, B), );
Int ans2 = KMP (min (len1, len2), len1 + len2 );
Int I;
If (ans1> ans2 ){
For (I = 0; I <len2; I ++) printf ("% c", B [I]);
For (I = ans1; I <len1; I ++) printf ("% c", a [I]);
}
Else if (ans2> ans1 ){
For (I = 0; I <len1; I ++) printf ("% c", a [I]);
For (I = ans2; I <len2; I ++) printf ("% c", B [I]);
}
Else {
If (strcmp (a, B)> 0 ){
For (I = 0; I <len2; I ++) printf ("% c", B [I]);
For (I = ans1; I <len1; I ++) printf ("% c", a [I]);
}
Else {
For (I = 0; I <len1; I ++) printf ("% c", a [I]);
For (I = ans2; I <len2; I ++) printf ("% c", B [I]);
}
}
Printf ("\ n ");
}
Return 0;
}