import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * User: student
 * Date: 10.11.13
 * Time: 10:31
 * To change this template use File | Settings | File Templates.
 */
public class J {
    static class Place
    {
        public Place(int f, int p)
        {
            floor = f;
            place = p;
        }
        public int floor;
        public int place;
    }

    public static int normalize(int val, int modulo)
    {
        if (val > modulo / 2) return val % modulo - modulo;
        if (val < -(modulo / 2)) return val % modulo + modulo;
        return val % modulo;
    }

    public static void main(String[] args) throws FileNotFoundException {
        Scanner scanner = new Scanner(new File("TOWER.IN"));
        
        int  T = scanner.nextInt();

        for (int i = 0; i < T; i++) {
            int H = scanner.nextInt();
            int L = scanner.nextInt();

            long total = 0;

            Place[] cars = new Place[H*L+1];
            int lastCar = 0;

            for (int j = 0; j < H; j++) {

                for (int k = 0; k < L; k++) {
                    int carNum= scanner.nextInt();

                    if (carNum != -1) {
                        cars[carNum] = new Place(j, k);
                        lastCar = Math.max(lastCar, carNum);
                    }
                }
            }

            int[] liftPlaces = new int[H];

            for (int j = 1; j <= lastCar; j++)
            {
                total += 20 * (cars[j].floor);
                int move = normalize(cars[j].place - liftPlaces[cars[j].floor], L);
                liftPlaces[cars[j].floor] = (liftPlaces[cars[j].floor] + move) % L;
                total += 5 * Math.abs(move);
            }

            System.out.println(total);
        }
    }

}
