FOo_bar_2's blog

By FOo_bar_2, 4 years ago, In English

Statement

You are given two strings a and b. Find shortest string which being repeated infinitely contains the both strings. I.e. find such shortest s that infinite string ss... s... contains a and contains b as a substring.

Constraints

  • $$$1 \le Number of Test Cases \le 100$$$
  • $$$1 \le len(a) \le 10000$$$
  • $$$1 \le len(b) \le 10000$$$

This problem is not from an ongoing contest. Those who have access to the group (Brazil ICPC Summer School 2018) can view it here!

  • Vote: I like it
  • +18
  • Vote: I do not like it

| Write comment?
»
4 years ago, # |
Rev. 3   Vote: I like it 0 Vote: I do not like it

I would follow the next steps:

  1. Check if a contains b or vice versa; if so, write the right string;

edit: check that this right string may be repeated string, like a = "dadada", b = "da"

  1. Check if a have a suffix that matches some prefix of b or vice versa; i.e. a = "cd", b = "da", then write "cda"

I think that's all. All of this you may do with only prefix function.

  • »
    »
    4 years ago, # ^ |
      Vote: I like it +5 Vote: I do not like it

    Try a = "cabc" and b = "bca" This won't work. Answer is s = "abc"

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

i think printing all the characters that appears in any one of the string would work

  • »
    »
    4 years ago, # ^ |
      Vote: I like it +5 Vote: I do not like it

    I think this only works for subsequence not substring.

»
3 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Break the problem into 2 subproblems:

  1. Find a string that contains both A and B, call it T
  2. Find the smallest string S which when repeated infinitely, has T as a substring

We will solve them separately, both utilize the knowledge of Longest proper prefix/Failure function.

Task 1

  1. If A is a substring of B then T = B
  2. If B is a substring of A then T = A
  3. T must be either A+B or B+A, but there will be some extra redundant characters. for A+B we must remove the largest prefix of B that is a suffix of A and then join A+B. Similarly for B+A. T1 = A+B, after reduction and T2 = B+A, after reduction.

Similar Idea — SPOJ — CF25E

Now we will try to form the string S from the above strings T (for T1 and T2, try both and pick the one which gives smaller S)

Task 2

We can consider the string as a circular string, it makes sense to remove the longest proper prefix that is also a suffix from T, then the leftover string when repeated infinite times will have T as the substring. Here we get the required string S.

abcab — LPS = ab, removing it gives "abc" which when repeated does give abc"abcab"c...

babab — LPS = bab, removing it gives "ab" which when repeated gives a"babab"aba...

Same Idea — A topcoder problem "Running Letters"