/*
ANALYSIS:
*/
#pragma GCC optimize(3);
#include <iostream>
#include <cstring>
#include <string>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <queue>
#include <stack>
#include <ctime>
#include <random>
#define int long long
#define endl '\n'
using namespace std;
const int N=2e3+5;
int n,m,dp[N][N],a[N],b[N];
void solution()
{
cin>>m>>n;
for (int i=1;i<=m;i++) cin>>a[m+1-i];
for (int i=1;i<=n;i++) cin>>b[n+1-i];
for (int i=1;i<=m;i++){
for (int j=1;j<=n;j++){
dp[i][j]=min(dp[i-1][j],dp[i][j-1])+1;
if (a[i]==b[j] || a[i]==1 || b[j]==1) dp[i][j]=min(dp[i][j],dp[i-1][j-1]+1);
}
}
int ans=N+N+N;
for (int i=1;i<=n;i++) ans=min(ans,dp[m][i]);
for (int i=1;i<=m;i++) ans=min(ans,dp[i][n]);
cout<<ans<<endl;
}
signed main() {
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
int T = 1;
//cin >> T;
for (int i=1;i<=T;i++) {
try {
cerr<<"Case #"<<i<<": "<<endl;
solution();
} catch (const char* e) {
cerr << "Caught exception in solution: " << e << endl;
}
}
return 0;
}