var t: text;
    i,j,k,n,H,L,max,c1,c2,x,y : integer;
    sum : longint;
    a : array[1..50, 1..50] of integer;
    now : array[1..50] of integer;
begin
        assign(t,'tower.in');
        reset(t);

        for i := 1 to 50 do
        now[i] := 0;
        readln(t,n);
        for i := 1 to n do begin
                max := 0;
                sum := 0;
          readln(t,h,l);
          for j := 1 to h do begin
            for k := 1 to l do begin
                read(t,a[j,k]);
                if (a[j,k] > max) then max := a[j,k];
            end;
            readln(t);

          end;

          for j := 1 to max do begin
            for c1 := 1 to h do
              for c2 := 1 to l do
                if (a[c1,c2] = j) then begin
                  x := c1;
                  y := c2;
                end;

//                writeln(x,' ',y,' ',now[x]);
            if abs(y-now[x]) <= abs(now[x]+l-y) then
            sum := sum+abs(y-now[x])*5 else
           sum := sum+abs(now[x]+l-y)*5;


//           writeln((x-1)*10);
//            if abs(y-now[x]) <= abs(now[x]+1+l-y) then writeln(abs(y-now[x])*5) else writeln(abs(now[x]+1+l-y)*5);
//            writeln((x-1)*10);


           now[x] := y;


            sum := sum+(x-1)*20;




          end;

            writeln(sum);

        end;
        close(t);
end.