program army;

{$APPTYPE CONSOLE}

uses
  SysUtils, System;
var
  fin: TextFile;
  line: string;
  n,m,i,j,h,h2,l,tests,emoe: integer;
  rote: array[1..10000] of integer;

begin
  { TODO -oUser -cConsole Main : Insert code here }
  AssignFile(fin,'army.in');
  Reset(fin);
  ReadLn(fin,line);
  tests:=StrToInt(line);
  for i:=1 to tests do begin
    emoe:=0;
    ReadLn(fin,line);
    n:=StrToInt(copy(line,0,pos(' ',line)-1));
    m:=StrToInt(copy(line,pos(' ',line)+1,length(line)-1-length(IntToStr(n))));
    for j:=1 to m do begin
      ReadLn(fin,line);
      l:=0;
      h:=1;
      while l<=length(line) do begin
        inc(l);
        if line[l]=' ' then begin
          rote[h]:=StrToInt(copy(line,0,l-1));
          line:=copy(line,l+1,length(line)-l);
          l:=0;
          inc(h);
        end;
      end;
      rote[h]:=StrToInt(line);
      for h:=1 to n do
        for h2:=1 to n do
          if (h<h2) and (rote[h]>rote[h2]) then inc(emoe);
    end;
    WriteLn(emoe);
  end;
end.
