Problem:


Score : 300 points

Problem Statement

You are given a string S of length N and another string T of length M.
These strings consist of lowercase English letters.

A string X is called a good string when the following conditions are all met:

Let L be the length of X. L is divisible by both N and M.

Concatenating the 1-st, (\frac{L}{N}+1)-th, (2 \times \frac{L}{N}+1)-th, ..., ((N-1)\times\frac{L}{N}+1)-th characters of X, without changing the order, results in S.

Concatenating the 1-st, (\frac{L}{M}+1)-th, (2 \times \frac{L}{M}+1)-th, ..., ((M-1)\times\frac{L}{M}+1)-th characters of X, without changing the order, results in T.

Determine if there exists a good string. If it exists, find the length of the shortest such string.

Constraints

1 \leq N,M \leq 10^5

S and T consist of lowercase English letters.

|S|=N

|T|=M

Input

Input is given from Standard Input in the following format:

N M
S
T

Output

If a good string does not exist, print -1; if it exists, print the length of the shortest such string.

Sample Input 1

3 2
acp
ae

Sample Output 1

6

For example, the string accept is a good string.
There is no good string shorter than this, so the answer is 6.

Sample Input 2

6 3
abcdef
abc

Sample Output 2

-1

Sample Input 3

15 9
dnsusrayukuaiia
dujrunuma

Sample Output 3

45



Sample input:
3 2
acp
ae


Sample output:
6

Submission status: Accepted

Solution code:
from fractions import gcd
x=input().split()
N=int(x[0])
M=int(x[1])
S=input()
T=input()
D=gcd(M,N)
OK=True
for l in range(D):
  if S[(l*N)//D]!=T[(l*M)//D]:
    OK=False
    break  
if OK==False:
  print(-1)
else:
  print((M*N)//D)

Submission status: Accepted

Solution code:
n, m = map(int, input().split())
s = input()
t = input()

from fractions import gcd

g = gcd(n, m)
l = n * m // g

for i in range(g):
    if s[i*n//g] != t[i*m//g]:
        print(-1)
        exit()
print(l)

Submission status: Accepted

Solution code:
def gcd(a, b):
    if a > b:
        a, b = b, a
    while a % b != 0:
        a, b = b, a % b
    return b

def lcm(a, b):
    return a * b // gcd(a, b)

def solve(n, m, s, t):
    if s == t:
        return n
    else:
        l = lcm(n, m)
        dx = l // n
        dy = l // m
        x = 0
        y = 0
        cx = 0
        cy = 0
        while cx < n and cy < m:
            if x == y:
                if s[cx] != t[cy]:
                    return -1
                x += dx
                cx += 1
                y += dy
                cy += 1
            elif x < y:
                x += dx
                cx += 1
            else:
                y += dy
                cy += 1
        return l

_n, _m = map(int, input().split())
_s = input()
_t = input()
print(solve(_n, _m, _s, _t))

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**6)
from math import floor,ceil,sqrt,factorial,log
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
from operator import itemgetter
from fractions import gcd
mod = 10 ** 9 + 7
 
#整数input
def ii(): return int(sys.stdin.readline().rstrip()) #int(input())
def mii(): return map(int,sys.stdin.readline().rstrip().split())
def limii(): return list(mii()) #list(map(int,input().split()))
def lin(n:int): return [ii() for _ in range(n)]
def llint(n: int): return [limii() for _ in range(n)]
#文字列input
def ss(): return sys.stdin.readline().rstrip() #input()
def mss(): return sys.stdin.readline().rstrip().split()
def limss(): return list(mss()) #list(input().split())
def lst(n:int): return [ss() for _ in range(n)]
def llstr(n: int): return [limss() for _ in range(n)]

#本当に貪欲法か？ DP法では？？
#本当に貪欲法か？ DP法では？？
#本当に貪欲法か？ DP法では？？

n,m=mii()
s=ss()
t=ss()
if len(s) < len(t):
    s,t=t,s
    n,m=m,n

p=n*m//gcd(n,m)
q=gcd(n,m)
if s[0]==t[0]:

    x,y=n//gcd(n,m),m//gcd(n,m)
    cnt=1

    for i in range(gcd(n,m)-1):
        if s[i*x]==t[i*y]:
            cnt+=1
    if cnt==q:
        print(p)
    else:
        print(-1)

else:
    print(-1)
#print(cnt,y)

Submission status: Accepted

Solution code:
import fractions
N, M = map(int, input().split())
S = input()
T = input()

if N < M:
    N, M = M, N
    S, T = T, S

if N % M == 0:
    print(N if all([S[(N // M) * i] == T[i] for i in range(M)]) else -1)
    exit()
else:
    g = fractions.gcd(N, M)
    print(N // g * M if all([S[(N // g) * i] == T[(M // g) * i] for i in range(g)]) else -1)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
import math
import os
import itertools
import string
import heapq
import _collections
from collections import Counter
from collections import defaultdict
from functools import lru_cache
import bisect
import re
import queue


class Scanner():
    @staticmethod
    def int():
        return int(sys.stdin.readline().rstrip())

    @staticmethod
    def string():
        return sys.stdin.readline().rstrip()

    @staticmethod
    def map_int():
        return [int(x) for x in Scanner.string().split()]

    @staticmethod
    def string_list(n):
        return [input() for i in range(n)]

    @staticmethod
    def int_list_list(n):
        return [Scanner.map_int() for i in range(n)]

    @staticmethod
    def int_cols_list(n):
        return [int(input()) for i in range(n)]


class Math():
    @staticmethod
    def gcd(a, b):
        if b == 0:
            return a
        return Math.gcd(b, a % b)

    @staticmethod
    def lcm(a, b):
        return (a * b) // Math.gcd(a, b)

    @staticmethod
    def roundUp(a, b):
        return -(-a // b)

    @staticmethod
    def toUpperMultiple(a, x):
        return Math.roundUp(a, x) * x

    @staticmethod
    def toLowerMultiple(a, x):
        return (a // x) * x

    @staticmethod
    def nearPow2(n):
        if n <= 0:
            return 0
        if n & (n - 1) == 0:
            return n
        ret = 1
        while(n > 0):
            ret <<= 1
            n >>= 1
        return ret

    @staticmethod
    def sign(n):
        if n == 0:
            return 0
        if n < 0:
            return -1
        return 1

    @staticmethod
    def isPrime(n):
        if n < 2:
            return False
        if n == 2:
            return True
        if n % 2 == 0:
            return False
        d = int(n ** 0.5) + 1
        for i in range(3, d + 1, 2):
            if n % i == 0:
                return False
        return True


class PriorityQueue:
    def __init__(self, l=[]):
        self.__q = l
        heapq.heapify(self.__q)
        return

    def push(self, n):
        heapq.heappush(self.__q, n)
        return

    def pop(self):
        return heapq.heappop(self.__q)


MOD = int(1e09) + 7
INF = int(1e15)


def calc(N):
    return sum(int(x) for x in str(N))


def main():
    # sys.stdin = open("sample.txt")
    N, M = Scanner.map_int()
    S = Scanner.string()
    T = Scanner.string()
    L = Math.lcm(N, M)
    s, t = 0, 0
    while s < N and t < M:
        if S[s] != T[t]:
            print(-1)
            return
        s += L//M
        t += L//N
    print(L)
    return


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N,M=map(int,input().split());import fractions;L=M//fractions.gcd(M,N)*N;print((-1,L)[input()[::L//M]==input()[::L//N]])

Submission status: Accepted

Solution code:
N,M=map(int,input().split())
import fractions
L=M//fractions.gcd(M,N)*N
print((-1,L)[input()[::L//M]==input()[::L//N]])

Submission status: Accepted

Solution code:
def gcd(a,b):
  if a<b:
    a,b=b,a
  while a%b>0:
    a,b=b,a%b
  return b

def lcm(a,b):
  return (a//gcd(a,b))*b

N,M=map(int,input().split())
S=input()
T=input()

length=lcm(N,M)
S=S[::length//M]
T=T[::length//N]
if S==T:
  print(length)
else:
  print(-1)

Submission status: Accepted

Solution code:
N,M=map(int,input().split())
S=input()
T=input()

def gcd(a,b):
  if a<b:
    a,b=b,a
  while a%b>0:
    a,b=b,a%b
  return b

def lcm(a,b):
  return (a//gcd(a,b))*b

length=lcm(N,M)
gapt=length//N
gaps=length//M
i=0
j=0
while i<N:
  if S[i]!=T[j]:
    print(-1)
    break
  else:
    i+=gaps
    j+=gapt
else:
  print(length)

Submission status: Accepted

Solution code:
n, m=map(int, input().split())
S=input()
T=input()

if n==1 and m==1:
  if S==T:
    print(1)
  else:
    print(-1)
  exit()
elif n==1 or m==1:
  print(-1)
  exit()

import fractions
p=n*m//fractions.gcd(n, m)
a=p//n
b=p//m
c=a*b//fractions.gcd(a, b)
for i in range(0, p, c):
  if S[i//a]!=T[i//b]:
    print(-1)
    exit()
    
print(p)

Submission status: Accepted

Solution code:
from fractions import gcd
def lcm(x,y):
    return x*y//gcd(x,y)
n,m = map(int,input().split())
s=input()
t=input()

l=lcm(n,m)
x=dict()

for i in range(n):
    x[i*(l//n)]=s[i]

for i in range(m):
    j=i*(l//m)
    if j in x and x[j]!=t[i]:
        print(-1)
        exit()
print(l)

Submission status: Accepted

Solution code:
# a,bの最大公約数
def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

# a,bの最小公倍数
def lcm(a, b):
    return a * b // gcd(a, b)


n,m = map(int,input().split())
s = input()
t = input()

lc = lcm(n,m)

dic = {}

for i in range(len(s)):
    dic[lc//n*i] = s[i]
for i in range(len(t)):
    if lc//m*i in dic:
        if dic[lc//m*i] != t[i]:
            print(-1)
            exit()

print(lc)

Submission status: Accepted

Solution code:
N, M = map(int, input().split())
S = input()
T = input()

def gcd(x, y):
    while y != 0:
        x, y = y, x % y
    return x

def lcm(x, y):
    return x // gcd(x, y) * y

L = lcm(N, M)
N_ = L // N
M_ = L // M

X = dict()
for i in range(N):
    X[i * N_] = S[i]

for i in range(M):
    j = i * M_
    if j in X and X[j] != T[i]:
        L = -1
        break

print(L)

Submission status: Accepted

Solution code:
def main():
    N, M = (int(i) for i in input().split())
    S = input()
    T = input()

    def gcd(x, y):
        if y == 0:
            return x
        while y != 0:
            x, y = y, x % y
        return x

    def lcm(x, y):
        return x*y//gcd(x, y)
    L = lcm(N, M)

    match = lcm(L//N, L//M)
    for a in range(0, L, match):
        if S[a * N//L] != T[a * M//L]:
            return print(-1)
    else:
        print(L)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#import sys
n, m = map(int, input().split())
s = input()
t = input()

if s[0] != t[0]:
    print(-1)
    exit()
    #sys.exit(0)

#a,bの最大公約数
def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

#a,bの最小公倍数
def lcm(a, b):
    return a * b // gcd (a, b)

l = lcm(n, m)
step = min(l//n, l//m)

for i in range(0, l, step):
    if i % (l//n) == 0 and i % (l//m) == 0:
        if s[i * n // l] != t[i * m // l]:
            print(-1)
            exit()
            # sys.exit(0)

print(l)

Submission status: Accepted

Solution code:
from sys import stdin
import fractions

#最小公倍数
def lcm(x, y):
    return (x * y) // fractions.gcd(x, y)

n,m = [int(x) for x in stdin.readline().rstrip().split()]
s = stdin.readline().rstrip()
t = stdin.readline().rstrip()
koubai = lcm(n,m)

if s[::koubai//m] == t[::koubai//n]:
    print(koubai)
else:
    print(-1)

Submission status: Accepted

Solution code:
from fractions import gcd
n,m = map(int,input().split())
s = input()
t = input()
x = gcd(n,m)
if s[::n//x]==t[::m//x]:
  print(n*m//x)
else:
  print(-1)

Submission status: Accepted

Solution code:
from fractions import gcd
n,m = map(int,input().split())
s = input()
t = input()
x = gcd(n,m)
for i in range(x):
  if s[i*n//x]!=t[i*m//x]:
    print(-1)
    break
else:
  print(n*m//x)

Submission status: Accepted

Solution code:
def gcd(a, b):
    while b != 0:
        a, b = b, a % b
    return a


def lcm(a, b):
    return a * b // gcd(a, b)


N, M = map(int, input().split())
S = input()
T = input()
gcd_val = gcd(N, M)
for i in range(gcd_val):
    if S[i * N // gcd_val] != T[i * M // gcd_val]:
        print(-1)
        exit()
print(lcm(N, M))

Submission status: Accepted

Solution code:
import fractions
N,M =list(map(int,input().split(" ")))
S = input()
T = input()
def lcm(x, y):
    return (x * y) // fractions.gcd(x, y)

ans = lcm(N,M)

step_S = ans //M
step_T = ans //N

ind_s = 0
ind_t = 0
while True:

    if ind_s >= N or ind_t >= M:
        break

    if S[ind_s ] != T[ind_t]:
        print(-1)
        exit(0)

    ind_s += step_S
    ind_t += step_T
print(ans)

Submission status: Accepted

Solution code:
import fractions
n, m = map(int, input().split())
s = input()
t = input()
sr = fractions.gcd(n, m)
sg, tg = n // sr, m // sr
for i in range(sr):
    if s[i * sg] != t[i * tg]:
        print(-1)
        exit()
print(sg * m)

Submission status: Accepted

Solution code:
import fractions
N,M = map(int,input().split())
S = input()
T = input()
gcd = fractions.gcd(N,M)
x = N // gcd 
y = M // gcd
check = 0
for i in range(gcd):
    if S[i*x] != T[i*y]:
        check = 1
        break
if check == 1:
    ans = -1
else:   
    ans = N * M // gcd
print(ans)

Submission status: Accepted

Solution code:
from fractions import gcd

N, M = map(int, input().split())

S = input()
T = input()

G = gcd(N, M)

n = N // G
m = M // G

L = N * M // G

for i in range(0, G):
    a = i * n
    b = i * m

    if S[a] != T[b]:
        print(-1)
        exit()

print(L)

Submission status: Accepted

Solution code:
import math
import sys

def gcd(a,b):
	if b == 0:
		return a
	return gcd(b,a%b)


n,m = map(int, input().split())
s = input()
t = input()

if s[0] != t[0]:
	print(-1)
	sys.exit()

GCD = gcd(n,m)

if GCD == 1:
	print(n*m)
	sys.exit()

LCM = n*m//GCD


s_k = LCM//m
t_k = LCM//n
for i in range(GCD):
	if s[i*s_k] != t[i*t_k]:
		print(-1)
		sys.exit()

print(LCM)

Submission status: Accepted

Solution code:
from fractions import gcd

N, M = map(int,input().split())
S = input()
T = input()
L = (N*M)//gcd(N,M)
S_a = L // N
T_a = L // M
L_a = (S_a*T_a)//gcd(S_a,T_a)

S_b = L_a // S_a
T_b = L_a // T_a
i = 0
j = 0
while True:
    if S[i] != T[j]:
        print('-1')
        break
    i += S_b
    j += T_b
    if i >= N or j >= M:
        print(L)
        break

Submission status: Accepted

Solution code:
from fractions import gcd
def lcm(a,b):
    return(a*b//gcd(a,b))

N,M=map(int,input().split())
S,T=input(),input()

_lcm=lcm(N,M)
n=_lcm//N
m=_lcm//M
for i in range(0,_lcm,n*m):
    if S[i//n]!=T[i//m]:
        print(-1)
        exit()    
print(_lcm)

Submission status: Accepted

Solution code:
import fractions

n, m = map(int, input().split())
s = input()
t = input()

l = n*m//fractions.gcd(n, m)

s_dic = {i * l//n + 1: s[i] for i in range(n)}
t_dic = {i * l//m + 1: t[i] for i in range(m)}

dup_idx = set(s_dic.keys()) & set(t_dic.keys())

for d in dup_idx:
    if s_dic[d] != t_dic[d]:
        print(-1)
        break
else:
    print(l)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def LS(): return list(map(list, input().split()))
def S(): return list(input().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = 1e10

#solve
def solve():
    n,m = LI()
    s = S()
    t = S()
    def gcd(a, b):
        while b:
            a, b = b, a % b
        return a
    g = gcd(n, m)
    l = n * m // g
    n_ = n // g
    m_ = m // g
    for i in range(g):
        if s[n_ * i] != t[m_ * i]:
            print(-1)
            return
    print(l)
    return


#main
if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
import bisect
import math
import sys
from collections import defaultdict
from copy import copy
from heapq import heapify, heappop, heappush, heapreplace
from operator import itemgetter
from queue import LifoQueue, PriorityQueue, Queue

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines


def main():
    N, M = map(int, readline().split())
    S, T = readlines()

    def gcd(a, b):
        while b > 0:
            a, b = b, a%b
        return a
    
    GCD = gcd(N, M)
    if S[0::N//GCD] == T[0::M//GCD]:
        print(N*M//GCD)
    else:
        print(-1)
    
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import bisect
import math
import sys
from collections import defaultdict
from copy import copy
from heapq import heapify, heappop, heappush, heapreplace
from operator import itemgetter
from queue import LifoQueue, PriorityQueue, Queue

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines


def main():
    N, M = map(int, readline().split())
    S, T = readlines()
    
    # NとMの最大公約数が1ならば、最初の文字が合っていれば構成可能
    n, m = copy(N), copy(M)
    while m != 0:
        n, m = m, n%m
    if n == 1:
        if S[0] == T[0]:
            print(N*M)
        else:
            print(-1)
            
    # NとMの最大公約数が1でなければ、ループして被る場所が同じになることを確認する必要がある
    else:
        L = N * M // n
        LN = L // N
        LM = L // M
        
        # LNとLMの最小公倍数をループして文字列一致を確認
        LCM = M // n * N // n
        for i in range(0, L, LCM):
            if S[i // LN] != T[i // LM]:    
                print(-1)
                sys.exit()

        print(L)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

from fractions import gcd

N,M = map(int,readline().split())
S = readline().rstrip().decode('utf-8')
T = readline().rstrip().decode('utf-8')

G = gcd(N,M)

# G回overlapする

A = ''.join(S[::N//G])
B = ''.join(T[::M//G])

if A == B:
    answer = N * M // G
else:
    answer = -1
print(answer)

Submission status: Accepted

Solution code:
import sys
import fractions
sys.setrecursionlimit(10**6)
if sys.platform in (['ios','darwin','win32']):
	sys.stdin=open('Untitled.txt')
input = sys.stdin.readline
def INT(): return int(input())
def MAP(): return [int(s) for s in input().split()]

def main():
	N, M = MAP()
	S = input().rstrip()
	T = input().rstrip()

	L = (N*M)//fractions.gcd(N, M)
	# print(L)
	n = L//N
	m = L//M
	for i in range(0, L, n):
		if i % m == 0:
			if S[i//n] != T[i//m]:
				print(-1)
				sys.exit()
	print(L)


if __name__ == '__main__':
	main()

Submission status: Accepted

Solution code:
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations,combinations
import sys
import bisect
import string
import math
import time
import random
def I():
    return int(input())
def MI():
    return map(int,input().split())
def LI():
    return [int(i) for i in input().split()]
def LI_():
    return [int(i)-1 for i in input().split()]
def StoI():
    return [ord(i)-97 for i in input()]
def ItoS(nn):
    return chr(nn+97)
def LtoS(ls):
    return ''.join(chr(i+97) for i in ls)
def GI(V,E,Directed=False,index=0):
    org_inp=[]
    g=[[] for i in range(n)]
    for i in range(E):
        inp=LI()
        org_inp.append(inp)
        if index==0:
            inp[0]-=1
            inp[1]-=1
        if len(inp)==2:
            a,b=inp
            g[a].append(b)
            if not Directed:
                g[b].append(a)
        elif len(inp)==3:
            a,b,c=inp
            aa=(inp[0],inp[2])
            bb=(inp[1],inp[2])
            g[a].append(bb)
            if not Directed:
                g[b].append(aa)
    return g,org_inp
def bit_combination(k,n=2):
    rt=[]
    for tb in range(n**k):
        s=[tb//(n**bt)%n for bt in range(k)]
        rt+=[s]
    return rt
def show(*inp,end='\n'):
    if show_flg:
        print(*inp,end=end)
YN=['Yes','No']
mo=10**9+7
inf=float('inf')
l_alp=string.ascii_lowercase
u_alp=string.ascii_uppercase
ts=time.time()
#sys.setrecursionlimit(10**5)
input=lambda: sys.stdin.readline().rstrip()

def ran_input():
    import random
    n=random.randint(4,16)
    rmin,rmax=1,10
    a=[random.randint(rmin,rmax) for _ in range(n)]
    return n,a

show_flg=False
show_flg=True

ans=inf

n,m=LI()
s=input()
t=input()
import fractions
g=fractions.gcd(n,m)

a,b=n//g,m//g

if s[::a]==t[::b]:
    print(n*m//g)
else:
    print(-1)

Submission status: Accepted

Solution code:
import fractions as f
n,m=map(int,input().split())
s=list(input())
t=list(input())
ans=0
N=n//f.gcd(n,m)
M=m//f.gcd(n,m)
for i in range(f.gcd(n,m)):
    if s[i*N]!=t[i*M]:
        ans=-1
        break
if ans!=-1:
    print(n*m//f.gcd(n,m))
else:
    print(-1)
#print(cnt)

Submission status: Accepted

Solution code:
from fractions import gcd
n,m=map(int,input().split())
s=input()
t=input()
if gcd(n,m)==1:
  if s[0]==t[0]:
    print(n*m)
  else:
    print(-1)
else:
  k=n//gcd(n,m)
  l=m//gcd(n,m)
  for i in range(gcd(n,m)):
    if s[i*k]!=t[i*l]:
      print(-1)
      exit()
  print(k*l*gcd(n,m))

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

from fractions import gcd

N,M = map(int,readline().split())
S = readline().rstrip().decode('utf-8')
T = readline().rstrip().decode('utf-8')

G = gcd(N,M)

# G回overlapする

A = ''.join(S[::N//G])
B = ''.join(T[::M//G])

if A == B:
    answer = N * M // G
else:
    answer = -1
print(answer)

Submission status: Accepted

Solution code:
import sys
def gcd(x,y):
    if x<y:
        x,y=y,x
    if y==0:
        return x
    else:
        return gcd(y,x%y)

N,M=map(int,input().split())
S=input()
T=input()
L=N*M//gcd(N,M)
n=L//N
m=L//M
l=n*m//gcd(n,m)
i=l//n
j=l//m
for k in range(N//i):
    if S[i*k]==T[j*k]:
        continue
    else:
        print(-1)
        sys.exit()
print(L)

Submission status: Accepted

Solution code:
def gcd(x,y):
    if x%y == 0:
        return y
    return gcd(y,x%y)
def lcm(x,y):
    return x//gcd(x,y)*y

N, M = map(int,input().split())
S = input()
T = input()

flag = True
K = gcd(N,M)
L = lcm(N,M)
for i in range(K):
    if S[i*N//K] != T[i*M//K]:
        flag = False
print(L if flag else -1)

Submission status: Accepted

Solution code:
"""a,bの最大公約数"""
def gcd(a,b):
    while b!=0:
        a,b=b,a%b
    return a


n,m=map(int,input().split())
s=input()
t=input()
g=gcd(n,m)
for i in range(g):
    if s[n//g*i]!=t[m//g*i]:
        print(-1)
        exit()
print(n*m//g)

Submission status: Accepted

Solution code:
from fractions import gcd
n, m = map(int, input().split())
s = input()
t = input()
g = gcd(n, m)
sg, tg = n//g, m//g
if s[::sg] != t[::tg]:
  print(-1)
else:
  print(sg*m)

Submission status: Accepted

Solution code:
from fractions import gcd
n, m = map(int, input().split())
s = input()
t = input()
g = gcd(n, m)
sg, tg = n//g, m//g
for i in range(g):
  if s[sg*i] != t[tg*i]:
    print(-1)
    break
else:
  print(sg*m)

Submission status: Accepted

Solution code:
N,M = map(int,input().split())
def gcd(a,b):
    if a >= b:
        if b == 0:
            return a
        else:
            return gcd(b,a%b)
    else:
        if a == 0:
            return b
        else:
            return gcd(a,b%a)
S = input()
T = input()
if S[0] != T[0]:
    print(-1)
else:
    flag = True
    L = int((N//gcd(N,M))*M)
    m = L//M
    n = L//N
    for i in range(max(N,M)):
        if i*m <= N-1 and i*n <= M-1:
            if S[i*m] != T[i*n]:
                flag = False
                break
    if flag:
        print(L)
    else:
        print(-1)

Submission status: Accepted

Solution code:
def gcd(x,y):
    while y>0:
        x,y = y,x%y
    return x
N,M = map(int,input().split())
S = input().strip()
T = input().strip()
a = gcd(N,M)
L = (N//a)*(M//a)*a
ks = L//N
kt = L//M
flag = 0
if S[0]!=T[0]:
    flag = 1
else:
    b = gcd(ks,kt)
    kl = (ks//b)*(kt//b)*b
    for i in range(min(N,M)):
        if (kl//ks)*i<N and (kl//kt)*i<M and S[(kl//ks)*i]!=T[(kl//kt)*i]:
            flag = 1
            break
if flag==1:
    print(-1)
else:
    print(L)

Submission status: Accepted

Solution code:
import sys
n, m = [int(i) for i in sys.stdin.readline().split()]
s = input()
t = input()

def gcd(a, b):
    while a and b:
        if a < b:
            b %= a
        else:
            a %= b
    return max(a, b)

_gcd = gcd(n, m)
if s[::n // _gcd] == t[::m // _gcd]:
    print(n * m // _gcd)
else:
    print(-1)

Submission status: Accepted

Solution code:
from fractions import gcd
from sys import exit, stdin
N, M = [int(_) for _ in stdin.readline().rstrip().split()]
S = stdin.readline().rstrip()
T = stdin.readline().rstrip()

def lcm(x, n, m):
    return x // gcd(n, m)
  
lcm_n, lcm_m = lcm(N, N, M), lcm(M, N, M)

if S[::lcm_n] != T[::lcm_m]:
    print(-1)
    exit()
print(lcm((N*M), N, M))

Submission status: Accepted

Solution code:
from fractions import gcd


def lcm(x,y):
    return (x*y)//gcd(x,y)


n,m=map(int,input().split())
s,t=input(),input()
lcm=lcm(n,m)

if s[::int(lcm/m)]!=t[::int(lcm/n)]:
    print(-1);exit()

print(lcm)

Submission status: Accepted

Solution code:
from fractions import gcd
def lcm(x,y):return (x*y)//gcd(x,y)
n,m=map(int,input().split())
s,t=input(),input()
lcm=lcm(n,m)
if s[::int(lcm/m)]!=t[::int(lcm/n)]:print(-1);exit()
print(lcm)

Submission status: Accepted

Solution code:
from fractions import gcd


def lcm(x,y):
    return (x*y)//gcd(x,y)


n,m=map(int,input().split())
s=input()
t=input()
lcm=lcm(n,m)
S=[(i,int(i*(lcm/n)+1)) for i in range(n)]
L=[(i,int(i*(lcm/m)+1)) for i in range(m)]
left,right=0,0
ans=[]
while left!=n and right!=m:
    if S[left][1]==L[right][1]:
        ans.append([S[left][0],L[right][0]])
        right +=1
        left +=1
    elif S[left][1]>L[right][1]:
        right +=1
    elif S[left][1]<L[right][1]:
        left +=1
for l,r in ans:
    if s[l]==t[r]:continue
    else:print(-1);exit()
print(lcm)

Submission status: Accepted

Solution code:
N, M = map(int, input().split())
S = input()
T = input()

def gcd(a, b) :
    if b > a : 
        a, b = b, a
    
    while b != 0 :
        a, b = b, a % b
    return a
    
def lcm(a, b) :
    return a * b // gcd(a, b)

for i in range(N) :
  if i * M % N != 0 :
    continue
  if S[i] != T[i * M // N] :
    print(-1)
    break
else :
  print(lcm(N, M))

Submission status: Accepted

Solution code:
from fractions import gcd
import sys
input = sys.stdin.readline

n, m = map(int, input().split())
s = input()
t = input()

g = gcd(n, m)
l = n * m // g
n = n // g
m = m // g
for i in range(g):
    if s[n * i] != t[m * i]:
        print(-1)
        exit()
print(l)

Submission status: Accepted

Solution code:
import fractions

N,M=map(int,input().split())
g=fractions.gcd(N,M)

a=N//g;b=M//g

S=input();T=input()

f=True
for k in range(g):
    if S[k*a]!=T[k*b]:
        f=False
        break

print(a*b*g if f else -1)

Submission status: Accepted

Solution code:
N, M = map(int, input().split())
S = input()
T = input()

def gcd(a, b):
    while b :
        a, b = b, a % b
    return a

def lcm(a, b):
    return a * b // gcd(a, b)

L = lcm(N, M)
s = L // M
t = L // N

if S[::s] != T[::t]:
    L = -1
print(L)

Submission status: Accepted

Solution code:
N, M = map(int, input().split())
S = input()
T = input()

D = [N, M]
while D[1] != 0:
  D[0], D[1] = D[1], D[0] % D[1]
R = D[0]
L = R * (N // R) * (M // R)
E = L
for i in range(R):
  if S[i * (L // M)] != T[i * (L // N)]:
    E = -1
print(E)

Submission status: Accepted

Solution code:
import fractions

def lcm(x, y):
    return (x * y) // fractions.gcd(x, y)

n, m = map(int, input().split())
s = input()
t = input()

if s[0] != t[0]:
    print(-1)
    exit()
    
l = lcm(n, m)
k = lcm(l//n, l//m)

for i in range(1, l//k):
    if s[i*k*n // l] != t[i*k*m // l]:
        print(-1)
        exit()
        
print(l)

Submission status: Accepted

Solution code:
import fractions
N, M = map(int, input().split())
S = input()
T = input()
ans = (N * M) // fractions.gcd(N, M)
n = N // fractions.gcd(N, M)
m = M // fractions.gcd(N, M)
for i in range(min(N // n, M // m)):
    tmpn = S[n * i]
    tmpm = T[m * i]
    if tmpn != tmpm:
        ans = -1
        break

print(ans)

Submission status: Accepted

Solution code:
# 2019-11-28 02:28:10(JST)
import sys

def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

def lcm(a, b):
    return a * b // gcd(a, b)

def main():
    n, m = map(int, sys.stdin.readline().split())
    s, t = sys.stdin.read().split()

    g = gcd(n, m)
    l = lcm(n, m)

    for i in range(g):
        if s[i * n // g] == t[i * m // g]:
            continue
        ans = -1
        break
    else:
        ans = l
    
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# 2019-11-28 02:28:10(JST)
import sys

def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

def lcm(a, b):
    return a * b // gcd(a, b)

def main():
    n, m = map(int, sys.stdin.readline().split())
    s, t = sys.stdin.read().split()

    g = gcd(n, m)
    l = lcm(n, m)

    if g == 1:
        if s[0] == t[0]:
            ans = l
        else:
            ans = -1
    else:
        for i in range(g):
            if s[i * n // g] == t[i * m // g]:
                continue
            else:
                ans = -1
                break
        else:
            ans = l
    
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:

from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
import itertools
from itertools import permutations, combinations
import sys
import bisect
import string
import math
import time
from fractions import gcd
#import random


def I(): return int(input())


def MI(): return map(int, input().split())


def MS(): return map(str, input().split())


def LI(): return [int(i) for i in input().split()]


def LI_(): return [int(i)-1 for i in input().split()]


def StoI(): return [ord(i)-97 for i in input()]


def ItoS(nn): return chr(nn+97)


def input(): return sys.stdin.readline().rstrip()


def show(*inp, end='\n'):
    if show_flg:
        print(*inp, end=end)


YN = ['Yes', 'No']
MOD = 10**9+7
inf = float('inf')
l_alp = string.ascii_lowercase
u_alp = string.ascii_uppercase
ts = time.time()
sys.setrecursionlimit(10**6)


# show_flg = False
show_flg = True


def lcm(a, b):
    return a * b // gcd(a, b)


def coprime(a, b):
    return gcd(a, b) == 1


def main():
    N, M = MI()
    S = input()
    T = input()

    LMC = lcm(N, M)

    if S[0] != T[0]:
        print(-1)
    else:
        a = LMC / N
        b = LMC / M
        abl = lcm(a, b)
        cur = 1
        while True:
            i = int(cur * abl * N // LMC)
            j = int(cur * abl * M // LMC)

            # print(i, j)

            if i >= N or j >= M:
                break

            if S[i] != T[j]:
                print(-1)
                return
            cur += 1

        print(LMC)


if __name__ == '__main__':
    main()