program Project1;

{$APPTYPE CONSOLE}
{
function Move(mv:boolean; step:byte; start:byte; len:byte):Byte; //0-D, 1-U
begin
   step:=step mod len;
   if step=0 then step:=len;
   if mv then
   begin
      result:=(start+step) mod len;
      if result=0 then result:=len;
   end
   else
   begin
      result:=(start-step);
      if result<1 then result:=result+len;
   end;
end;   }

type
   TArr= array of integer;
   TArray = array of TArr;

var
   f:textfile;
   ar:TArray;
   T:byte;
   H,L,i,k,j,dx,b:byte;
   Summ:Cardinal;
   ex:boolean;
 //  lvlar:TLvlAr;
   find:boolean;
   lvl,ind:byte;

procedure Move(var ar:TArr; step:byte; left:boolean);
var
   i:byte;
   d:TArr;
begin
   if left then
   begin
      SetLength(d,step);
      for i:=0 to step-1 do
         d[i]:=ar[i];
      for i:=step to high(ar) do
         ar[i-step]:=ar[i];
      for i:=0 to high(d) do
         ar[Length(ar)-step+i]:=d[i];
   end
   else
   begin
      SetLength(d,step);
      for i:=0 to step-1 do
         d[i]:=ar[Length(ar)-step+i];
      for i:=Length(ar)-step-1 downto 0 do
         ar[i+step]:=ar[i];
      for i:=0 to high(d) do
         ar[i]:=d[i];
   end;
end;

function Calculate(lev:byte;var ar:TArr; ind:byte):Cardinal;
var
   k:byte;
begin
   if Length(ar)-ind<ind then
   begin
      k:=Length(ar)-ind;
      Move(ar,k,false);
   end
   else
   begin
      k:=ind;
      Move(ar,ind,true);
   end;
   Result:=lev*20+k*5;
end;

begin
   AssignFile(f,'TOWER.IN');
   Reset(f);
   readln(f,T);
   for i:=1 to T do
   begin
      Summ:=0;
      readln(f,h,l);
      SetLength(Ar,h);
      for k:=0 to high(ar) do
      begin
         SetLength(ar[k],l);
         if l>1 then
            for j:=0 to high(ar[k])-1 do
               read(f,ar[k][j]);
         readln(f,ar[k][high(ar[k])]);
      end;
      for dx:=1 to h*l do
      begin
         ex:=false;
         find:=false;
         for b:=0 to high(ar) do
         begin
            for j:=0 to high(ar[b]) do
               if ar[b][j]=dx then
               begin
                  lvl:=b;
                  ind:=j;
                  ex:=true;
                  find:=true;
                  break;
               end;
            if ex then  break;
         end;
         if find then
            Summ:=Summ+Calculate(lvl,ar[lvl],ind);
         if not find then break;
      end;
      writeln(Summ);
   end;
   Close(f);
end.
