#include #include #include #include #include #include #include #include #include #include #include using namespace std; typedef long long ll; int main() { int N, M; cin >> N >> M; vector A(N); vector B(M); for (int i = 0; i < N; ++i) { cin >> A[i]; } for (int i = 0; i < M; ++i) { cin >> B[i]; } for (int i = 0; i < N * M; ++i) { if (A[i % N] != B[i % M]) continue; cout << i + 1 << endl; return 0; } cout << -1 << endl; return 0; }