//NWERC-2007-H

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

#include <string>
#include <vector>
#include <set>
#include <map>
#include <algorithm>

using namespace std;

#define VI vector<int>
#define int64 long long
#define VVI vector <vector<int> >

#define SZ(a) a.size()
#define MP make_pair
#define PB push_back
#define ALL(a) a.begin(), a.end()
#define CLA(a) memset(a, 0, sizeof(a))
#define FOR(i,n) for (int i = 0; i < int(n); i++)
#define FORR(i,n) for (int i = n - 1; i >=0; i--)
#define REP(n) for (int _foo = n - 1; _foo >= 0; _foo--)

#define INF 1000000000

int ri() {int t; scanf("%d", &t); return t;}
void rs(char *s) {scanf("%s", s);}
void pi(int n){printf("%d\n", n);}

int n, res, m;

int a[64][64], sh[64];

int x[64*64];
int y[64*64];

void solve()
{
	res = 0;
	int k = 1;
	while (x[k] >= 0)
	{
		int xx = x[k], yy = y[k];
		// floor
		res += 2 * xx * 10;
		// place
		int posl = sh[xx], posr = sh[xx];
		sh[xx] = yy;
		while (posl != yy && posr != yy)
		{
			posl = (posl + 1) % m;
			posr = (posr - 1 + m) % m;
			res += 5;
		}
		k++;
	}
}	

int main()
{
#ifdef _DEBUG
	freopen("in.txt", "r", stdin);
	//freopen("out.txt", "w", stdout);
#endif

	REP(ri())
	{
		CLA(x); CLA(y); CLA(sh);
		FOR(i,64*64) x[i] = y[i] = -1;

		n = ri();
		m = ri();
		FOR(i,n) FOR(j,m)
		{
			int t = ri();
			a[i][j] = t;
			if (t > 0)
				x[t] = i, y[t] = j;
		}
		solve();
		pi(res);
	}

}