#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

vector<int> sdv(vector<int> v, int k)
{
	vector<int> copy;
		for(int i=k;i<v.size();++i)
		{
			copy.push_back(v[i]);
		}
		for(int i=0;i<k;++i)
			copy.push_back(v[i]);
	return copy;
}

int main()
{
	ifstream in("TOWER.IN");

	int n;
	in>>n;
	while(n--)
	{
		int H,L;
		in>>H>>L;
		vector<vector<int>> v;
		vector<int> tempv;
		int max=-1;
		for(int i=0;i<H;++i)
		{
			tempv.clear();
			for(int j=0;j<L;++j)
			{
				int temp;
				in>>temp;
				if(max<temp) max=temp;
				tempv.push_back(temp);
			}
			v.push_back(tempv);
		}
		int TIME=0;
		int cur=1;
		a:while(cur!=max+1)
		{
			for(int i=0;i<H;++i)
			{
				for(int j=0;j<L;++j)
				{
					if(v[i][j]==cur)
					{
						if(j<=v[i].size()/2)
							TIME+=j*5;
						else
							TIME+=(L-j)*5;
						v[i]=sdv(v[i],j);
						TIME+=i*20;
						cur++;
						goto a;
					}
				}
			}
		}
		cout<<TIME<<endl;
	}
	return 0;
}