using static System.Math; using System.Linq; using System.Collections.Generic; using System; public class P { public int aa { get; set; } public int bb { get; set; } } public class Hello { public static int n, m; static void Main() { string[] line = Console.ReadLine().Trim().Split(' '); n = int.Parse(line[0]); m = int.Parse(line[1]); line = Console.ReadLine().Trim().Split(' '); var a = Array.ConvertAll(line, int.Parse); line = Console.ReadLine().Trim().Split(' '); var b = Array.ConvertAll(line, int.Parse); var ps = new List

(); for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (a[i] == b[j]) ps.Add(new P { aa = i, bb = j }); getAns(ps); } static void getAns(List

ps) { var ans = int.MaxValue; if (ps.Count() == 0) { Console.WriteLine(-1); return; } var tmax = Max(n, m); foreach (var x in ps) { for (int L = 0; L <= tmax; L++) for (int k = 0; k <= tmax; k++) { if ((m * L + x.bb - x.aa) % n == 0) { var p = m * L + x.bb; ans = Min(ans, p); } } } Console.WriteLine(ans + 1); } }