def read_data(): N = int(input()) K = int(input()) amida = list(range(N)) for k in range(K): x, y = map(int, input().split()) amida[x-1], amida[y-1] = amida[y-1], amida[x-1] Q = int(input()) As = [] for q in range(Q): a = list(map(int, input().split())) As.append(a) return N, amida, Q, As def solve(N, amida, Q, As): cycles = [0] * N pos = [[-1] * N for n in range(N)] for idx in range(N): find_cycle(N, amida, idx, cycles, pos[idx]) shuffle = [chinese_remainder(a, cycles, pos) for a in As] return shuffle def find_cycle(N, amida, idx, cycles, mypos): mypos[idx] = 0 a = amida[idx] count = 1 while a != idx: mypos[a] = count a = amida[a] count += 1 cycles[idx] = count def chinese_remainder(a, cycles, pos): xy = [] for ai, cycle, mypos in zip(a, cycles, pos): x = mypos[ai - 1] if x == -1: return -1 xy.append((x, cycle)) return CRT(xy) def gcd_ext(m, n): x, y, u, v = 1, 0, 0, 1 while n: k, m = divmod(m, n) m, n = n, m x, y, u, v = u, v, x - u * k, y - v * k return m, x, y def solve2(x1, y1, x2, y2): gcd, a, b = gcd_ext(y1, y2) lcm = y1 * y2 // gcd k, r = divmod(x1 - x2, gcd) if r != 0: return -1, lcm z = (x1 - k * a * y1) % lcm return z, lcm def CRT(xy): x0, y0 = xy[0] if len(xy) == 1: return x0 if x0 else y0 for x1, y1 in xy[1:]: x0, y0 = solve2(x0, y0, x1, y1) if x0 == -1: return -1 return x0 if x0 else y0 N, amida, Q, As = read_data() shuffles = solve(N, amida, Q, As) for shuffle in shuffles: print(shuffle)