#include #include #include #include #include #include #include #include #include using namespace std; #define rep(i,n) for (int i = 0; i < (n); ++i) #define all(x) (x).begin(),(x).end() typedef long long ll; using P = pair; #define INF 1001001001 #define LINF (1LL<<60) #define F first #define S second template inline bool chmax(T& a, T b){ if(a inline bool chmin(T& a, T b){ if(a>b){ a=b; return 1; } return 0; } int main() { int n, m; cin >> n >> m; vector a(n); rep(i, n) cin >> a[i]; vector b(m); rep(i, m) cin >> b[i]; int ans = -1; rep(i, n*m+1) { if (a[i%n] == b[i%m]) { ans = i+1; break; } } cout << ans << endl; }