PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#GL0000313. Hai cách viết tắt (Two Abbreviations)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Hai cách viết tắt (Two Abbreviations)

Two Abbreviations

Source: AtCoder

Version: Phuoc Hung OJ Extended

Problem Statement

You are given two lowercase English strings SS and TT of lengths NN and MM. Construct a string XX of length LL, where LL is divisible by both NN and MM.

Taking characters of XX at positions 1,1+L/N,1+2L/N,…,1+(N−1)L/N1,1+L/N,1+2L/N,\ldots,1+(N-1)L/N in this order must produce SS.

Similarly, the characters at positions 1,1+L/M,1+2L/M,…,1+(M−1)L/M1,1+L/M,1+2L/M,\ldots,1+(M-1)L/M must produce TT.

Find the minimum possible length of a string XX satisfying both conditions, or print -1 if no such string exists. Unconstrained positions may contain any lowercase letter.

Input

  • The first line contains two integers N,MN,M.
  • The second line contains string SS of length NN.
  • The third line contains string TT of length MM.

Output

Print the smallest valid length LL, or -1 if no such string exists.

Subtasks

  • Subtask 0 (20 points): 1≤N,M≤101\le N,M\le 10; ∣S∣=N|S|=N, ∣T∣=M|T|=M; every character of S,TS,T is a lowercase English letter.
  • Subtask 1 (30 points): 1≤N,M≤20001\le N,M\le 2000; ∣S∣=N|S|=N, ∣T∣=M|T|=M; every character of S,TS,T is a lowercase English letter.
  • Subtask 2 (50 points): 1≤N,M≤1000001\le N,M\le 100000; ∣S∣=N|S|=N, ∣T∣=M|T|=M; every character of S,TS,T is a lowercase English letter.

Examples

Example 1

Input

3 2
acp
ae

Output

6

Explanation

For L=6L=6, positions 1,3,51,3,5 are a, c, p, while positions 1,41,4 are a, e. The string accept satisfies both requirements; 66 is also the least common positive multiple of 33 and 22.

Example 2

Input

6 3
abcdef
abc

Output

-1

Explanation

At the least common multiple length L=6L=6, SS requires position 33 to be c, but TT (selected at positions 1,3,51,3,5) requires position 33 to be b. These requirements conflict at every larger common multiple as well.

Example 3

Input

15 9
dnsusrayukuaiia
dujrunuma

Output

45

Explanation

The least common multiple of 1515 and 99 is 4545. The two selections overlap at gcd⁡(15,9)=3\gcd(15,9)=3 positions, and the required characters match at each overlap, so 4545 is valid.