# include <fstream>
# include <iostream>
# include <string>
# include <vector>
# include <queue>
# include <climits>
using namespace std;
int shift[51];
int l,h;
double mid;
int mass[51][51];
int getRes(int x)
{
	int res=0;
	for(int i=0; i<h; i++)
	{
		int t=shift[i];
		int cnt=0;
		int Res=0;
		while(cnt<l)
		{
			if(mass[i][t]==x)
			{
				shift[i]+=cnt;
				if(shift[i]>=l)
					shift[i]-=l;
				int p=res+Res;
					return p;
			}
			if(l%2==1)
			{
			if(cnt<mid)
			Res+=5;
		
			else if(cnt>mid)
				Res-=5;
			}
			else
			{
				if(cnt<=mid-1)
			Res+=5;
		
			else if(cnt>mid-1)
				Res-=5;
			}
             cnt++;
			t++;
			 if(t==l)
				 t=0;

		}
		res+=20;
	}
	
}
void main ()
{
	ifstream in("TOWER.IN");
	int n;
	in>>n;
	in.sync_with_stdio(false);
	for(int i=0; i<n; i++)
	{
		memset(shift,0,51*sizeof(int));
		
		int mx=-1;
		in>>h>>l;
		mid=l/2;
		for(int j=0; j<h; j++)
			for(int k=0; k<l; k++)
			{
				in>>mass[j][k];
				if(mass[j][k]>mx)
					mx=mass[j][k];
			}
			long long ans=0;
			for(int i=1; i<=mx; i++)
				ans+=getRes(i);
			cout<<ans<<endl;
			//system("pause");
	}
	
}


