#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ld long double
#define pb push_back
const ll MOD = 1e9+7;

bool sprawdz(vector<vector<int>> & grid, int n, int k, int value){
	vector<vector<int>> edit(n+1, vector<int>(n+1));
	vector<vector<int>> sums(n+1, vector<int>(n+1, 0));
	for(int i = 1; i<=n; i++){
		for(int j = 1; j<=n; j++){
			if(grid[i][j] <= value){
				edit[i][j] = 1;
			}
			else{
				edit[i][j] = 0;
			}
			sums[i][j] = sums[i-1][j] + sums[i][j-1] - sums[i-1][j-1] + edit[i][j];
		}
	}
	for(int i = k; i<=n; i++){
		for(int j = k; j<=n; j++){
			if(sums[i][j] - sums[i-k][j] - sums[i][j-k] + sums[i-k][j-k] >= (k*k+1)/2 ){
				return true;
			}
		}
	}
	return false;
}

void solve()
{
	int n, k;
	cin >> n >> k;
	vector<vector<int>> grid(n+1, vector<int>(n+1));
	int MIN = INT_MAX;
	int MAX = 0;
	for(int i = 1; i<=n; i++){
		for(int j = 1; j<=n; j++){
			cin >> grid[i][j];
			MIN = min(MIN, grid[i][j]);
			MAX = max(MAX, grid[i][j]);
		}
	}
	int start = MIN, end = MAX;
	while(start < end){
		int mid = (start+end)/2;
		if(sprawdz(grid, n, k, mid)){
			end = mid;
		}
		else{
			start = mid+1;
		}
	}
	cout << start << endl;


}

int main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	bool testcases = false;
	if (testcases)
	{
		int t;
		cin >> t;
		while (t--)
		{
			solve();
		}
	}
	else
	{
		solve();
	}
	return 0;
}

#include <bits/stdc++.h>
using namespace std;

typedef long long int ll;
#define deb(x) cout << #x << " " << x << endl;
#define debtwo(x,y) cout << x << ", " << y << endl;
#define mod 1000000007
#define N 1000001

void solve() {
	ll n, m;
	cin >> n >> m;
	vector<ll> arr(n), brr(m);
	for (ll &x : arr) cin >> x;
	for (ll &x : brr) cin >> x;

	ll dp[n + 1][m + 1];
	memset(dp, 0, sizeof dp);

	for (int j = 1; j <= m; j++) dp[0][j] = j;

	for (int i = 1; i <= n; i++) {
		dp[i][0] = i;
		for (int j = 1; j <= m; j++) {
			if (arr[i - 1] == brr[j - 1]) {
				dp[i][j] = min({1 + dp[i][j - 1], 1 + dp[i - 1][j], dp[i - 1][j - 1]});
			}
			else {
				dp[i][j] = min({1 + dp[i][j - 1], 1 + dp[i - 1][j], 1 + dp[i - 1][j - 1]});
			}
		}
	}
	// cout << "x   ";
	// for (int i = 1; i <= m; i++) cout << brr[i - 1] << " "; cout << endl;
	// for (int i = 0; i <= n; i++) {
	// 	if (i != 0) cout << arr[i - 1] << " ";
	// 	else cout << "  ";
	// 	for (int j = 0; j <= m; j++) {
	// 		cout << dp[i][j] << " ";
	// 	}
	// 	cout << endl;
	// }

	cout << dp[n][m];
}

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);

	ll t = 1;
	//cin >> t;

	while (t--) {
		solve();
	}
}