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

Solution in C# (Mono 4.6.2.0) (judge verdict: Runtime Error)

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;

namespace AGC028A
{
    class Program
    {
        static void Solve(Input input)
        {
            var n = input.NextInt();
            var m = input.NextInt();
            var s = input.Next();
            var t = input.Next();

            // xの長さはnとmの公倍数
            var len = Number.Lcm(n, m);

            var x = new char[len];
            for (int i = 0; i < n; i++)
            {
                x[i * len / n] = s[i];
            }

            var y = new char[x.Length];
            for (int i = 0; i < m; i++)
            {
                y[i * len / m] = t[i];
            }

            if (!x.Zip(y, (a, b) => a == 0 || b == 0 || a == b).All(a => a))
            {
                len = -1;
            }
            Console.WriteLine(len);
        }

        /// <summary>
        /// 最大公約数
        /// 最小公倍数
        /// 拡張ユークリッド互除法
        /// nPm, nCr
        /// </summary>
        static class Number
        {
            /// <summary>
            /// 最大公約数
            /// ユークリッド互除法
            /// </summary>
            /// <param name="a"></param>
            /// <param name="b"></param>
            /// <returns></returns>
            public static long Gcd(long a, long b)
            {
                long r;

                while ((r = a % b) != 0)
                {
                    a = b;
                    b = r;
                }

                return b;
            }

            /// <summary>
            /// 最大公約数
            /// </summary>
            /// <param name="nums"></param>
            /// <returns></returns>
            public static long Gcd(IEnumerable<long> nums)
                => nums.Aggregate((n, next) => n = Gcd(n, next));

            public static int Gcd(IEnumerable<int> nums)
                => (int)Gcd(nums.Select(x => (long)x));

            /// <summary>
            /// 最小公倍数
            /// </summary>
            /// <param name="a"></param>
            /// <param name="b"></param>
            /// <returns></returns>
            public static long Lcm(long a, long b)
                => a / Gcd(a, b) * b;

            /// <summary>
            /// 最小公倍数
            /// </summary>
            /// <param name="nums"></param>
            /// <returns></returns>
            public static long Lcm(IEnumerable<long> nums)
                => nums.Aggregate((n, next) => n = Lcm(n, next));

            /// <summary>
            /// 最小公倍数
            /// </summary>
            /// <param name="nums"></param>
            /// <returns></returns>
            public static long Lcm(IEnumerable<int> nums)
                => Lcm(nums.Select(x => (long)x));

            /// <summary>
            /// 拡張ユークリッドの互除法
            /// ax+by = gcd(a,b)の整数解
            /// </summary>
            /// <param name="a"></param>
            /// <param name="b"></param>
            /// <param name="x"></param>
            /// <param name="y"></param>
            /// <returns></returns>
            public static void ExtendedGcd(long a, long b, out long x, out long y)
            {
                long u = 0, v = 1;
                x = 1; y = 0;

                while (b > 0)
                {
                    long q = a / b;
                    long t;

                    t = u;
                    u = x - q * u;
                    x = t;

                    t = v;
                    v = y - q * v;
                    y = t;

                    t = b;
                    b = a - q * b;
                    a = t;
                }
            }

            /// <summary>
            /// ルジャンドルの公式
            /// n!をpで何回割り切れるか
            /// </summary>
            /// <param name="n">正の整数</param>
            /// <param name="p">素数</param>
            /// <returns></returns>
            public static long Legendres(long n, long p)
            {
                long count = 0;
                for (long m = p; m < n; m *= p)
                {
                    count += n / m;
                }

                return count;
            }

            /// <summary>
            /// n!
            /// 12! < int(2^31 - 1) < 13!
            /// 20! < long(2^63 - 1) < 21!
            /// </summary>
            /// <param name="n"></param>
            /// <returns></returns>
            public static long Factorial(long n)
            {
                var m = 1L;

                for (long i = 2; i <= n; i++)
                {
                    m *= i;
                }

                return m;
            }

            /// <summary>
            /// nPr
            /// </summary>
            /// <param name="n"></param>
            /// <param name="r"></param>
            /// <returns></returns>
            public static long Permutation(long n, long r)
            {
                var m = n;

                for (long i = n - 1; i > n - r; i--)
                {
                    m *= i;
                }

                return m;
            }

            /// <summary>
            /// nCr
            /// </summary>
            /// <param name="n"></param>
            /// <param name="r"></param>
            /// <returns></returns>
            public static long Combination(long n, long r)
            {
                return Permutation(n, r) / Factorial(r);
            }
        }

        #region Main
        public static void Main(string[] args)
        {
            // 出力が少ないときはこれをセットする方が時間かかるけれど
            // その場合は出力がボトルネックになっていないので、まあ良しとする
            var needsFlushOutput = true;
            if (needsFlushOutput)
            {
                // 細かく出力しないようにする
                var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false };
                Console.SetOut(sw);
            }

            // 通常は引数無しで、ファイルから読み出したい場合はpath指定する
            var input = new Input();
            // 仮想的に標準入力をセットする
            //input.SetText("");

            Solve(input);

            Console.Out.Flush();
        }
        #endregion

        #region Competitive Template
#pragma warning disable CS0414
        static readonly int MOD = (int)1e9 + 7;
#pragma warning restore CS0414

        class Input
        {
            // 変な改行コードがたまに混じっているので、一応セパレート指定する
            // スペース単独指定の方がもちろん早い
            static readonly char[] separator = { ' ', '\r', '\n' };
            Queue<string> q { get; set; }
            StreamReader sr;

            /// <summary>
            /// 特定のファイルから読み出したい場合はpath指定する
            /// </summary>
            /// <param name="path"></param>
            public Input(string path = "")
            {
                q = new Queue<string>();

                if (string.IsNullOrEmpty(path))
                {
                    sr = new StreamReader(Console.OpenStandardInput());
                }
                else
                {
                    sr = new StreamReader(path);
                }
            }

            /// <summary>
            /// 入力予約
            /// </summary>
            /// <param name="items"></param>
            public void SetText(IEnumerable<string> items)
            {
                foreach (var item in items)
                {
                    SetText(item);
                }
            }

            /// <summary>
            /// 入力予約
            /// </summary>
            /// <param name="s"></param>
            /// <returns></returns>
            public bool SetText(string s)
            {
                if (s == null) return false;

                foreach (var elem in s.Trim().Split(separator, StringSplitOptions.RemoveEmptyEntries))
                {
                    q.Enqueue(elem);
                }

                return true;
            }

            /// <summary>
            /// 内部queueに入力からの値をsplitして格納する
            /// </summary>
            /// <returns></returns>
            bool read()
            {
                var s = sr.ReadLine();
                if (s == null) return false;

                foreach (var elem in s.Trim().Split(separator, StringSplitOptions.RemoveEmptyEntries))
                {
                    q.Enqueue(elem);
                }

                if (!q.Any()) return read();

                return true;
            }

            /// <summary>
            /// 次のstringを一つ読み込む
            /// </summary>
            /// <returns></returns>
            public string Next()
            {
                if (!q.Any())
                {
                    if (!read())
                    {
                        return "";
                    }
                }

                return q.Dequeue();
            }

            /// <summary>
            /// 指定個数queueにたまるまでenqueueし続ける
            /// </summary>
            /// <param name="n"></param>
            /// <returns></returns>
            bool accumulate(int n)
            {
                while (q.Count() < n)
                {
                    if (!read()) return false;
                }

                return true;
            }

            public int NextInt() => int.Parse(Next());
            public long NextLong() => long.Parse(Next());
            public double NextDouble() => double.Parse(Next());

            /// <summary>
            /// n個の要素をparseして、それぞれにoffsetをaddした配列を返す
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="n"></param>
            /// <param name="offset"></param>
            /// <param name="parse"></param>
            /// <param name="add"></param>
            /// <returns></returns>
            T[] NextT<T>(int n, T offset, Func<string, T> parse, Func<T, T, T> add)
            {
                if (!accumulate(n)) return null;

                var a = new T[n];

                for (int i = 0; i < n; i++)
                    a[i] = add(parse(q.Dequeue()), offset);

                return a;
            }

            public string[] Next(int n) => NextT(n, "", x => x, (x, y) => x);
            public int[] NextInt(int n, int offset = 0) => NextT(n, offset, int.Parse, (x, y) => x + y);
            public long[] NextLong(int n, long offset = 0) => NextT(n, offset, long.Parse, (x, y) => x + y);
            public double[] NextDouble(int n, double offset = 0.0) => NextT(n, offset, double.Parse, (x, y) => x + y);
        }

        static class Utils
        {
            public static void Print<T>(IEnumerable<T> ie, string sep = " ") => Console.WriteLine(string.Join(sep, ie));
            public static void Print<T>(params T[] objs) => Print(objs);
            public static T Max<T>(params T[] objs) => objs.Max();
            public static T Min<T>(params T[] objs) => objs.Min();

            public static void Swap<T>(ref T x, ref T y) where T : struct { var t = x; x = y; y = t; }
            public static void Swap<T>(IList<T> list, int i, int j) where T : struct { var t = list[i]; list[i] = list[j]; list[j] = t; }

            /// <summary>
            /// vでfillされたT[d1][d2]配列を作成する
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="d1"></param>
            /// <param name="d2"></param>
            /// <param name="v"></param>
            /// <returns></returns>
            public static T[][] Create2DArray<T>(int d1, int d2, T v = default(T))
            {
                return
                    Enumerable.Repeat(0, d1).Select(_ =>
                    Enumerable.Repeat(v, d2).ToArray()).ToArray();
            }

            /// <summary>
            /// vでfillされたT[d1][d2][d3]配列を作成する
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="d1"></param>
            /// <param name="d2"></param>
            /// <param name="d3"></param>
            /// <param name="v"></param>
            /// <returns></returns>
            public static T[][][] Create3DArray<T>(int d1, int d2, int d3, T v = default(T))
            {
                return
                    Enumerable.Repeat(0, d1).Select(_ =>
                    Enumerable.Repeat(0, d2).Select(__ =>
                     Enumerable.Repeat(v, d3).ToArray()).ToArray()).ToArray();
            }
        }
        #endregion
    }
}