#include "bits/stdc++.h" using namespace std; #define FOR(i,j,k) for(int (i)=(j);(i)<(int)(k);++(i)) #define rep(i,j) FOR(i,0,j) #define each(x,y) for(auto &(x):(y)) #define mp make_pair #define all(x) (x).begin(),(x).end() #define debug(x) cout<<#x<<": "<<(x)< pii; typedef vector vi; typedef vector vll; long long gcd(long long a, long long b){ return b?gcd(b, a%b):a; } vector exgcd(long long a, long long b){ if(b==0) return vector{1, 0, a}; auto res = exgcd(b, a%b); return vector{res[1], res[0]-a/b*res[1], res[2]}; } pair crt( long long a0, long long m0, long long a1, long long m1){ long long g = gcd(m0, m1); if(a0%g != a1%g)return make_pair(-1, -1); if(g > 1){ m0 /= g; m1 /= g; ll h; while((h = gcd(m0, g)) != 1){ m0 *= h; g /= h; } m1 *= g; a0 %= m0; a1 %= m1; } vector r = exgcd(m0, m1); ll p = r[0], q = r[1]; g = r[2]; ll x = a0 * q * m1 + a1 * p * m0; ll m = m0 * m1; x %= m; return make_pair(x, m); } int main(){ int N, K; cin >> N >> K; vi a(N); iota(all(a), 0); rep(i, K){ int x, y; cin >> x >> y; swap(a[--x], a[--y]); } int Q; cin >> Q; while(Q--){ vi b(N), rb(N); rep(i, N){ cin >> b[i]; --b[i]; rb[b[i]] = i; } ll y = 0, m = 1, ok = 1; rep(i, N){ int l = 0, p = i, x = -1; do{ if(rb[p] == i)x = l; p = a[p]; l++; } while(p != i); if(x == -1){ ok = 0; break; } tie(y, m) = crt(y, m, x, l); if(m == -1){ ok = 0; break; } } if(y == 0)y = m; cout << (ok ? y : -1) << endl; } }