#include "bits/stdc++.h" using namespace std; #ifdef _DEBUG #include "dump.hpp" #else #define dump(...) #endif //#define int long long #define rep(i,a,b) for(int i=(a);i<(b);i++) #define rrep(i,a,b) for(int i=(b)-1;i>=(a);i--) #define all(c) begin(c),end(c) const int INF = sizeof(int) == sizeof(long long) ? 0x3f3f3f3f3f3f3f3fLL : 0x3f3f3f3f; const int MOD = 1'000'000'007; template bool chmax(T &a, const T &b) { if (a < b) { a = b; return true; } return false; } template bool chmin(T &a, const T &b) { if (b < a) { a = b; return true; } return false; } // 拡張ユークリッドの互除法 // 一次不定方程式 ax + by = gcd(a, b) を満たす x, y を求める // ax + by = k * gcd(a, b) は、まず ax + by = gcd(a, b) を解き、解を k 倍する // 戻り値: gcd(a, b) long long extgcd(long long a, long long b, long long &x, long long &y) { long long g = a; x = 1; y = 0; if (b != 0) { g = extgcd(b, a % b, y, x); y -= (a / b) * x; } return g; } // 中国剰余定理 pair crt(const vector &a, const vector &n) { assert(a.size() == n.size()); long long A = 0, N = 1; for (int i = 0; i < a.size(); i++) { long long u, v; long long g = extgcd(N, n[i], u, v); if (a[i] % g != A % g) return make_pair(-1, -1); long long m = n[i] / g; long long t = (a[i] - A) / g * u % m; A += N * t; N *= m; } A %= N; if (A < 0)A += N; return make_pair(A % N, N); } int gcd(int x, int y) { return y ? gcd(y, x % y) : x; } int lcm(int x, int y) { return x / gcd(x, y) * y; } signed main() { cin.tie(0); ios::sync_with_stdio(false); int N, K; cin >> N >> K; vector X(K), Y(K); rep(i, 0, K) { cin >> X[i] >> Y[i]; X[i]--, Y[i]--; } vector v(N); iota(all(v), 0); rep(i, 0, K) swap(v[X[i]], v[Y[i]]); int Q; cin >> Q; vector> A(Q, vector(N)); rep(i, 0, Q) rep(j, 0, N) { cin >> A[i][j]; A[i][j]--; } vector g(N); vector> r(N, vector(N, -1)); int l = 1; rep(i, 0, N) { int c = 1; r[i][i] = 0; for (int s = v[i]; s != i; s = v[s]) { r[i][s] = c; c++; } g[i] = c; l = lcm(l, c); } dump(r); rep(q, 0, Q) { vector a, n; rep(i, 0, N) { a.push_back(r[i][A[q][i]]); n.push_back(g[i]); } if(count(all(a),-1)) cout << -1 << endl; else { auto res = crt(a, n); if(res.first == -1) cout << -1 << endl; else if(res.first == 0) cout << l << endl; else cout << res.first << endl; } } return 0; }