It is the hard version of the problem. The only difference is that in this version 1 ≤ n ≤ 300.

In the cinema seats can be represented as the table with n rows and m columns. The rows are numbered with integers from 1 to n. The seats in each row are numbered with consecutive integers from left to right: in the k-th row from m (k - 1) + 1 to m k for all rows 1 ≤ k ≤ n.

1| 2| ⋅⋅⋅| m - 1| m  
---|---|---|---|---  
m + 1| m + 2| ⋅⋅⋅| 2 m - 1| 2 m  
2m + 1| 2m + 2| ⋅⋅⋅| 3 m - 1| 3 m  
\vdots| \vdots| \ddots| \vdots| \vdots  
m (n - 1) + 1| m (n - 1) + 2| ⋅⋅⋅| n m - 1| n m  
The table with seats indices

There are nm people who want to go to the cinema to watch a new film. They are numbered with integers from 1 to nm. You should give exactly one seat to each person.

It is known, that in this cinema as lower seat index you have as better you can see everything happening on the screen. i-th person has the level of sight a_i. Let's define s_i as the seat index, that will be given to i-th person. You want to give better places for people with lower sight levels, so for any two people i, j such that a_i < a_j it should be satisfied that s_i < s_j.

After you will give seats to all people they will start coming to their seats. In the order from 1 to nm, each person will enter the hall and sit in their seat. To get to their place, the person will go to their seat's row and start moving from the first seat in this row to theirs from left to right. While moving some places will be free, some will be occupied with people already seated. The inconvenience of the person is equal to the number of occupied seats he or she will go through.

Let's consider an example: m = 5, the person has the seat 4 in the first row, the seats 1, 3, 5 in the first row are already occupied, the seats 2 and 4 are free. The inconvenience of this person will be 2, because he will go through occupied seats 1 and 3.

Find the minimal total inconvenience (the sum of inconveniences of all people), that is possible to have by giving places for all people (all conditions should be satisfied).

Input

The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Description of the test cases follows.

The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 300) — the number of rows and places in each row respectively.

The second line of each test case contains n ⋅ m integers a_1, a_2, …, a_{n ⋅ m} (1 ≤ a_i ≤ 10^9), where a_i is the sight level of i-th person.

It's guaranteed that the sum of n ⋅ m over all test cases does not exceed 10^5.

Output

For each test case print a single integer — the minimal total inconvenience that can be achieved.

Example

Input


7
1 2
1 2
3 2
1 1 2 2 3 3
3 3
3 4 4 1 1 1 1 1 2
2 2
1 1 2 1
4 2
50 50 50 50 3 50 50 50
4 2
6 6 6 6 2 2 9 6
2 9
1 3 3 3 3 3 1 1 3 1 3 1 1 3 3 1 1 3


Output


1
0
4
0
0
0
1

Note

In the first test case, there is a single way to give seats: the first person sits in the first place and the second person — in the second. The total inconvenience is 1.

In the second test case the optimal seating looks like this: 

<image>

In the third test case the optimal seating looks like this: 

<image>

The number in a cell is the person's index that sits on this place.
import static java.util.Arrays.*;

import java.util.*;

public class D2 {

	public Object solve () {
		R = sc.nextInt(); C = sc.nextInt();
		int [] A = sc.nextInts();

		int Z = R * C;
		A = compress(A);
		int [] B = sort(A.clone());
		int [] P = new int [Z], Q = new int [Z], T = new int [Z];


		P[B[0]] = 0;
		for (int i : rep(1, Z))
			if (B[i] != B[i-1]) {
				Q[B[i-1]] = i-1;
				P[B[i]] = i;
			}
		Q[B[Z-1]] = Z-1;

		for (int a : B) {
			int p = P[a], q = Q[a];
			if (q / C > p / C)
				T[a] = (int) ceil(p+1, C) * C - 1;
			else
				T[a] = q;
			assert T[a] >= 0;
		}

		Fenwick F = new Fenwick(Z);
		long res = 0;

		for (int i : rep(Z)) {
			int a = A[i];
			int t = calc(T, B, P[a], Q[a], a);
			int r = t / C;
			res += F.get(r*C, t);
			F.add(1, t);
		}

		return res;
	}

	int R, C;

	int calc (int [] T, int [] B, int p, int q, int a) {
		int x = T[a], r = x / C, c = x % C;
		assert x >= 0;

		if (c > 0 && B[x-1] == a) {
			T[a] = x-1;
			return x;
		}

		int y = (r+1) * C + (C-1);
		if (y < R*C && B[y] == a) {
			T[a] = y;
			assert T[a] >= 0;
			return x;
		}

		T[a] = q;
		assert T[a] >= 0;
		return x;
	}

	private static final int CONTEST_TYPE = 2;

	private static void init () {
	}

	private static Integer [] boxed (int ... A) { return stream(A).mapToObj(x -> x).toArray(Integer[]::new); }
	private static long ceil (long p, long q) { return Round.round(p, q, true); }
	private static int [] compress (int [] A) {
		Set<Integer> S = new HashSet<>();
		for (int a : A)
			S.add(a);
		Map<Integer, Integer> B = vtk(S.stream().sorted().toArray(Integer[]::new));
		int [] res = new int [A.length];
		for (int i = 0; i < A.length; ++i)
			res[i] = B.get(A[i]);
		return res;
	}
	private static int [] rep (int N) { return rep(0, N); }
	private static int [] rep (int S, int T) { if (S >= T) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[i-S] = i; return res; }
	private static int [] sort (int [] A) { Integer [] AA = boxed(A); Collections.shuffle(asList(AA)); Arrays.sort(unboxed(AA, A)); return A; }
	private static int [] unboxed (Integer [] A) { return stream(A).mapToInt(x -> x).toArray(); }
	private static int [] unboxed (Integer [] A, int [] a) { System.arraycopy(unboxed(A), 0, a, 0, A.length); return a; }
	private static <T> Map<T, Integer> vtk (@SuppressWarnings("unchecked") T ... A) {
		Map<T, Integer> res = new TreeMap<>();
		for (int i = 0; i < A.length; ++i)
			res.put(A[i], i);
		return res;
	}
	private static class Fenwick {
		private final long [] X;
		private final long mod;
		public Fenwick (int N) { this(N, 0); }
		public Fenwick (int N, int mod) { X = new long [N]; this.mod = mod; }
		public void add (long x, int i) {
			++i; assert i <= X.length;
			while (i <= X.length) {
				X[i-1] += x;
				if (mod > 0) X[i-1] = ((X[i-1] % mod) + mod) % mod;
				i += (i & (-i));
			}
		}
		public long get (int to) {
			assert to <= X.length;
			long res = 0;
			for (; to > 0; to -= (to & (-to))) {
				res += X[to-1];
				if (mod > 0) res = ((res % mod) + mod) % mod;
			}
			return res;
		}
		public long get (int from, int to) {
			assert from <= to;
			long res = get(to) - get(from);
			if (mod > 0) res = ((res % mod) + mod) % mod;
			return res;
		}
	}
	private static class Round {
		private static long round (long p, long q, boolean up) {
			if (q < 0) return round(-p, -q, up);
			if (p < 0) return -round(-p, q, !up);
			return (p + (up ? q-1 : 0)) / q;
		}
	}
	//////////////////////////////////////////////////////////////////////////////////// OFF
	private static IOUtils.MyScanner sc = new IOUtils.MyScanner();
	private static class IOUtils {
		public static class MyScanner {
			public String next () { newLine(); return line[index++]; }
			public int nextInt () { return Integer.parseInt(next()); }
			public String nextLine () { line = null; return readLine(); }
			public String [] nextStrings () { return split(nextLine()); }
			public int [] nextInts () {
				String [] S = nextStrings(); int N = S.length;
				int [] res = new int [N];
				for (int i = 0; i < N; ++i)
					res[i] = Integer.parseInt(S[i]);
				return res;
			}
			//////////////////////////////////////////////
			private boolean eol () { return index == line.length; }
			private String readLine () {
				try {
					int b;
					StringBuilder res = new StringBuilder();
					while ((b = System.in.read()) < ' ')
						continue;
					res.append((char)b);
					while ((b = System.in.read()) >= ' ')
						res.append((char)b);
					return res.toString();
				} catch (Exception e) {
					throw new Error (e);
				}
			}
			private MyScanner () {
				try {
					while (System.in.available() == 0)
						Thread.sleep(1);
					start();
				} catch (Exception e) {
					throw new Error(e);
				}
			}
			private String [] line;
			private int index;
			private void newLine () {
				if (line == null || eol()) {
					line = split(readLine());
					index = 0;
				}
			}
			private String [] split (String s) { return s.length() > 0 ? s.split(" ") : new String [0]; }
		}
		private static String build (Object o, Object ... A) { return buildDelim(" ", o, A); }
		private static String buildDelim (String delim, Object o, Object ... A) {
			java.util.List<String> str = new java.util.ArrayList<>();
			append(str, o);
			for (Object p : A)
				append(str, p);
			return String.join(delim, str.toArray(new String [0]));
		}
		//////////////////////////////////////////////////////////////////////////////////
		private static java.text.DecimalFormat formatter = new java.text.DecimalFormat("#.#########");
		private static void start () { if (t == 0) t = millis(); }
		private static void append (java.util.function.Consumer<Object> f, java.util.function.Consumer<Object> g, Object o) {
			if (o.getClass().isArray()) {
				int len = java.lang.reflect.Array.getLength(o);
				for (int i = 0; i < len; ++i)
					f.accept(java.lang.reflect.Array.get(o, i));
			}
			else if (o instanceof Iterable<?>)
				((Iterable<?>)o).forEach(f::accept);
			else
				g.accept(o instanceof Double ? formatter.format(o) : o);
		}
		private static void append (java.util.List<String> str, Object o) {
			append(x -> append(str, x), x -> str.add(x.toString()), o);
		}
		private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out);
		private static void flush () { pw.flush(); System.out.flush(); }
		private static void print (Object o, Object ... A) {
			String res = build(o, A);
			if (DEBUG == 2)
				err(res, '(', time(), ')');
			if (res.length() > 0)
				pw.println(res);
			if (DEBUG == 1)
				flush();
		}
		private static void err (Object o, Object ... A) { System.err.println(build(o, A)); }
		private static int DEBUG;
		private static void exit () {
			String end = "------------------" + System.lineSeparator() + time();
			switch(DEBUG) {
			case 1: print(end); break;
			case 2: err(end); break;
			}
			IOUtils.pw.close();
			System.out.flush();
			System.exit(0);
		}
		private static long t;
		private static long millis () { return System.currentTimeMillis(); }
		private static String time () { return "Time: " + (millis() - t) / 1000.0; }
		private static void run (int N) {
			try { DEBUG = Integer.parseInt(System.getProperties().get("DEBUG").toString()); }
			catch (Throwable t) {}

			for (int n = 1; n <= N; ++n) {
				Object res = new D2().solve();
				if (res != null) {
					@SuppressWarnings("all")
					Object o = CONTEST_TYPE == 0 ? "Case #" + n + ": " + build(res) : res;
					print(o);
				}
			}
			exit();
		}
	}
	////////////////////////////////////////////////////////////////////////////////////
	public static void main (String[] args) {
		@SuppressWarnings("all")
		int N = CONTEST_TYPE == 1 ? 1 : sc.nextInt();
		init();
		IOUtils.run(N);
	}
}
