#include <iostream>
#include <deque>

using namespace std;

int main(){
	freopen ("TOWER.IN","r",stdin);

	int am_tests;
	cin>>am_tests;

	for (int test=0;test<am_tests;test++){
		
		deque <int> tower[50];
		for (int i = 0; i<50; i++){
				tower[i].clear();
		}
			
		int H, L;
		int por_y[10000],por_x[10000], max = 0;
		cin >> H >> L;
		
		for (int i = 0; i<H; i++){
			for (int j = 0; j<L; j++){
				int temp;
				cin >> temp;
				tower[i].push_back(temp);		
			}
		}

		for (int i = 0; i<H; i++){
			for (int j = 0; j<L; j++){
				if (tower[i][j] > 0){
					por_y[tower[i][j]] = i;
					if (tower[i][j] > max) {max = tower[i][j];};
				}; 
			}
		}
	
	

	
		int time = 0;
		for (int i = 1; i < max+1; i++){
			int sdvig = 0;		
			for (int j = 0; j<L; j++){
				if (tower[por_y[i]][j] == i){
					if (i >= L/2){
					sdvig = (L-1-i)*-1;
					}
					else sdvig = i;
					}
				}
			if (por_y[i] == 0){ time+=0; }
			else { time += 10*(por_y[i])*2;};
			while (tower[por_y[i]][0] != i){
				if (sdvig < 0){
					tower[por_y[i]].push_front(tower[por_y[i]][L-1]);
					tower[por_y[i]].pop_back();
					time += 5;
				}
				else{
					tower[por_y[i]].push_back(tower[por_y[i]][0]);
					tower[por_y[i]].pop_front();
					time += 5;
				
				}
				
			}
			tower[por_y[i]][0] = -1;
		}
		cout << endl << time;
		
		
	}
	return 0;
}