#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; #pragma GCC optimize("O3") #pragma GCC optimize("unroll-loops") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native") #pragma GCC target("avx512f,avx512dq,avx512cd,avx512bw,avx512vl") using ll = long long; constexpr int INF = 1001001001; // constexpr int mod = 1000000007; constexpr int mod = 998244353; template inline bool chmax(T& x, T y){ if(x < y){ x = y; return true; } return false; } template inline bool chmin(T& x, T y){ if(x > y){ x = y; return true; } return false; } int main(){ ios::sync_with_stdio(false); cin.tie(nullptr); int n, m; cin >> n >> m; vector a(n), b(m); for(int i = 0; i < n; ++i) cin >> a[i]; for(int i = 0; i < m; ++i) cin >> b[i]; while(a.size() < 30000000){ for(int i = 0; i < n; ++i) a.emplace_back(a[i]); } while(b.size() < 30000000){ for(int i = 0; i < m; ++i) b.emplace_back(b[i]); } for(int i = 0; i < 30000000; ++i){ if(a[i] == b[i]){ cout << i + 1 << endl; return 0; } } cout << -1 << endl; return 0; }