#include <bits/stdc++.h>
#define LL long long
using namespace std;
template <typename T> void read(T &x){
	x = 0; int f = 1; char ch = getchar();
	while (!isdigit(ch)) {if (ch == '-') f = -1; ch = getchar();}
	while (isdigit(ch)) {x = x * 10 + ch - '0'; ch = getchar();}
	x *= f;
}
inline void write(int x){if (x > 9) write(x/10); putchar(x%10+'0'); }

const int P = 998244353;
const int N = 5050;
int n,m;
LL pw[N][N],pre[N][N];
int main(){
//	cerr << sizeof(pw)*2.0/1024/1024<<'\n';
	register int i,j;
	LL ans = 0;
	read(n),read(m);
	for (i = 1; i <= 5000; ++i)
	for (pw[i][0] = j = 1; j <= 5000; ++j) pw[i][j] = pw[i][j-1] * i % P;
	pw[0][0] = 1;
	for (i = 1; i < n; ++i)
	for (j = 0; j <= m; ++j){
		if (j) pre[i][j] = (pre[i-1][j] + pre[i][j-1] - pre[i-1][j-1] + pw[j][i-1] * pw[m][n-i-1]) % P;
		else pre[i][j] = (pre[i-1][j] + pw[j][i-1] * pw[m][n-i-1]) % P;
	}
	
	LL s1,s2,s3 = 0;
	for (i = 1; i <= n; ++i){
		s1 = pw[m-1][i-1] * pw[m][n-i] % P;
		s2 = (pw[m][n] - s1 + P) % P;
		ans = (ans + s1 + s2) % P;
		s3 = pre[i-1][m-1];
		ans = (ans - s3 + P) % P; 
	}
	ans = (ans % P + P) % P;
	cout << ans << '\n';
	return 0;
}
#include<stdio.h>

int n,m,a[1002],b[1002],dp[1002][1002];

inline int min(int x,int y){return x<y?x:y; }
inline int min(int x,int y,int z){ return min(x,min(y,z)); }

int main()
{
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++)
		scanf("%d",&a[i]),dp[i][0]=i;
	for(int i=1;i<=m;i++)
		scanf("%d",&b[i]),dp[0][i]=i;
	for(int i=1;i<=n;i++)
		for(int j=1;j<=m;j++)
			dp[i][j]=min(dp[i-1][j]+1,dp[i][j-1]+1,dp[i-1][j-1]+(a[i]!=b[j]));
	printf("%d",dp[n][m]);
	return 0;
}