You have a stripe of checkered paper of length $$$n$$$. Each cell is either white or black.What is the minimum number of cells that must be recolored from white to black in order to have a segment of $$$k$$$ consecutive black cells on the stripe?If the input data is such that a segment of $$$k$$$ consecutive black cells already exists, then print 0.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Next, descriptions of $$$t$$$ test cases follow. The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2\cdot10^5$$$). The second line consists of the letters 'W' (white) and 'B' (black). The line length is $$$n$$$. It is guaranteed that the sum of values $$$n$$$ does not exceed $$$2\cdot10^5$$$.

For each of $$$t$$$ test cases print an integer — the minimum number of cells that need to be repainted from white to black in order to have a segment of $$$k$$$ consecutive black cells.

4

5 3

BBWBW

5 5

BBWBW

5 1

BBWBW

1 1

W

NoteIn the first test case, $$$s$$$="BBWBW" and $$$k=3$$$. It is enough to recolor $$$s_3$$$ and get $$$s$$$="BBBBW". This string contains a segment of length $$$k=3$$$ consisting of the letters 'B'.In the second test case of the example $$$s$$$="BBWBW" and $$$k=5$$$. It is enough to recolor $$$s_3$$$ and $$$s_5$$$ and get $$$s$$$="BBBBB". This string contains a segment of length $$$k=5$$$ consisting of the letters 'B'.In the third test case of the example $$$s$$$="BBWBW" and $$$k=1$$$. The string $$$s$$$ already contains a segment of length $$$k=1$$$ consisting of the letters 'B'.

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}

const solve = () => {
  const gcd = (a, b) => (a % b === 0 ? b : gcd(b, a % b));
  let t = parseInt(readline());
  while (t--) {
       let [n,k] = readline().trim().split(" ").map(cur=>parseInt(cur));
       let arr = readline().trim().split("");
       let min = Infinity,i=0,cnt = 0,j=0;
       while(i<k) if(arr[i++]==="W") cnt++;
       min = Math.min(min,cnt);
       let l;
       while(i<n){
            l = cnt;
            if(arr[i]==="W") l++;
            if(arr[j]==="W") l--;
            min = Math.min(l,min);
            cnt = l;
            i++;
            j++;
       }
       console.log(min);
  }
};
solve();

const fs = require('fs');
const input = fs.readFileSync(0, 'utf8').trim().split('\n');

let currentline = 0;
function readline(){
    return input[currentline++];
}

let t = +readline();

while(t--){
    let [n , k] = readline().trim().split(' ').map(x=>+x);
    let str = readline().trim();
    console.log(`${solve(str, n, k)}`)
}

function solve(str, n, k){
    let result = n;
    let currW = 0;
    for(let i = 0; i < n; i++){
        if(str[i] === 'W') currW++;

        if(i-k +1 >= 0){
            result = Math.min(result, currW);
            if(str[i-k+1] === "W") currW--;
        }
        if(result === 0) break;
    }
    return result;
}

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const [n, k] = lines[l++].trim().split(' ').map(Number)
        const str = lines[l++]
        output[i] = solve(n, k, str)
    }
    console.log(output.join('\n'))
// })()
})

let F
function inc(idx, val) {
    for (; idx < F.length; idx |= idx + 1) {
        F[idx] += val
    }
}
function sum(idx) {
    let s = 0
    for (; idx >= 0; idx = (idx & (idx + 1)) - 1) {
        s += F[idx]
    }
    return s
}

function solve(n, k, str) {
    F = Array(n + 5).fill(0)
    for (let i = 0; i < str.length; i++) {
        if (str[i] === 'B') {
            inc(i, 1)
        }
    }
    let ans = Infinity
    for (let i = 0; i + k - 1 < str.length; i++) {
        // [i, i + k - 1]
        const d = sum(i + k - 1) - (i ? sum(i - 1) : 0)
        // console.log(i, k - d)
        ans = Math.min(ans, k - d)
    }
        // console.log('-')
    return ans
}

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = []; var outputList = [];var retcode = new Set();
read.on('line', function(input){
	var tmp = input.split(' ');
	for(var i = 0; i < tmp.length; i++){
		inLine.push(tmp[i]);
		if(i == tmp.length - 1){
			retcode.add(inLine.length);
		}
	}
});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
	console.log(myconv(outputList, 9));
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextArray(size, code){
	var ret = new Array(size);
	for(var i = 0; i < size; i++){
		if(code == 'int'){
			ret[i] = nextInt();
		}else if(code == 'long'){
			ret[i] = nextLong();
		}else if(code == 'double'){
			ret[i] = nextDouble();
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}
function getCountMap(list){
	var map = {};
	for(var i = 0; i < list.length; i++){
		if(map[list[i]] == null){
			map[list[i]] = 0;
		}
		map[list[i]]++;
	}
	return map;
}
function init(input){
	return {
		list : input, index : 0, max : input.length,
		hasNext : function(){return (this.index < this.max);},
		next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},
		isReturn : function(){return retcode.has(this.index);}
	};
}
function myout(s){outputList.push(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
function isReturn(){return obj.isReturn();}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var K = nextInt();
		var list = next();
		var sum = new Array(N + 1).fill(0);
		for(var i = 0; i < N; i++){
			if(list[i] == "W"){
				sum[i + 1]++;
			}
			sum[i + 1] += sum[i];
		}
		var output = 1000000000;
		for(var i = 0; i < N - K + 1; i++){
			output = Math.min(output, sum[i + K] - sum[i]);
		}
		myout(output);
	}
}

'use strict';

function solve(n, m, s) {
  const sum = new Array(n);
  for (let i = 0; i < n; i++) {
    var _sum;
    sum[i] = ((_sum = sum[i - 1]) !== null && _sum !== void 0 ? _sum : 0) + (s[i] === 'B' ? 0 : 1);
  }
  let res = Infinity;
  for (let i = m - 1; i < n; i++) {
    var _sum2;
    res = Math.min(res, sum[i] - ((_sum2 = sum[i - m]) !== null && _sum2 !== void 0 ? _sum2 : 0));
  }
  return res;
}

async function main(read) {
  try {
    let res = [];
    let t = Number(await read());
    while (t--) {
      const [n, m] = (await read()).split(' ').map(Number);
      const s = await read();
      res.push(solve(n, m, s));
    }
    console.log(res.join('\n'));
  } catch (error) {
    console.log(error);
  }
}

let inputs,
    str = '';
function read() {
  return inputs.next().value.trim();
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', () => {
  inputs = str.split('\n').values();
  main(read);
});

var tests = parseInt(readline());
    var n, k;
    var s;
    for (var t=0; t < tests; t++) {
        var nk = readline().split(' ').map(x=>parseInt(x));
        n = nk[0];
        k = nk[1];
        var s = readline();
        var dict = {
            B: 0,
            W: 0,
        }
        for (var i = 0; i < k; i++) {
            dict[s.charAt(i)]++;
        }
        var minW = dict.W;
        for (var i = k; i < n; i++) {
            dict[s.charAt(i)]++;
            dict[s.charAt(i-k)]--;
            if (dict.W < minW) {
                minW = dict.W;
            }
        }
        print(minW);
    }


There are n pearls in a row. Let's enumerate them with integers from 1 to n from the left to the right. The pearl number i has the type ai.Let's call a sequence of consecutive pearls a segment. Let's call a segment good if it contains two pearls of the same type.Split the row of the pearls to the maximal number of good segments. Note that each pearl should appear in exactly one segment of the partition.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.

The first line contains integer n (1 ≤ n ≤ 3·105) — the number of pearls in a row. The second line contains n integers ai (1 ≤ ai ≤ 109) – the type of the i-th pearl.

On the first line print integer k — the maximal number of segments in a partition of the row. Each of the next k lines should contain two integers lj, rj (1 ≤ lj ≤ rj ≤ n) — the number of the leftmost and the rightmost pearls in the j-th segment. Note you should print the correct partition of the row of the pearls, so each pearl should be in exactly one segment and all segments should contain two pearls of the same type. If there are several optimal solutions print any of them. You can print the segments in any order. If there are no correct partitions of the row print the number "-1".

var pearlsAmount = readline();
var typesOfPearls = readline().split(' ');
var segmentsEndPoints = [];
var amountOfSegments = 0;
var object = {};
for (var i = 0; i < pearlsAmount; i++) {
    if (object[typesOfPearls[i]]) {
        amountOfSegments++;
        segmentsEndPoints.push(i+1);
        object = {};
    } else {
        object[typesOfPearls[i]] = 1;
    }
}

if (amountOfSegments == 0) {
    print("-1");
} else {
    segmentsEndPoints.pop();
    segmentsEndPoints.push(pearlsAmount);
    print(amountOfSegments);
    var startPoint = 1;
    for (var i = 0; i < amountOfSegments; i++) {
        print(startPoint + " " + segmentsEndPoints[i]);
        startPoint = segmentsEndPoints[i] + 1;
    }
}

var pearlsAmount = readline();
var typesOfPearls = readline().split(' ');
var segmentsEndPoints = [];
var amountOfSegments = 0;
var typesExistence = [];
for (var i = 0; i < pearlsAmount; i++) {
    if (typesExistence[typesOfPearls[i]]) {
        amountOfSegments++;
        segmentsEndPoints.push(i+1);
        typesExistence.length = 0;
    } else {
        typesExistence[typesOfPearls[i]] = 1;
    }
}

if (amountOfSegments == 0) {
    print("-1");
} else {
    segmentsEndPoints.pop();
    segmentsEndPoints.push(pearlsAmount);
    print(amountOfSegments);
    var startPoint = 1;
    for (var i = 0; i < amountOfSegments; i++) {
        print(startPoint + " " + segmentsEndPoints[i]);
        startPoint = segmentsEndPoints[i] + 1;
    }
}

var pearlsAmount = readline();
var typesOfPearls = readline().split(' ');
var segmentsEndPoints = [];
var amountOfSegments = 0;
var typesExistence = [];
for (var i = 0; i < pearlsAmount; i++) {
    if (typesExistence[typesOfPearls[i]]) {
        amountOfSegments++;
        segmentsEndPoints.push(i+1);
        typesExistence = [];
    } else {
        typesExistence[typesOfPearls[i]] = 1;
    }
}

if (amountOfSegments == 0) {
    print("-1");
} else {
    segmentsEndPoints.pop();
    segmentsEndPoints.push(pearlsAmount);
    print(amountOfSegments);
    var startPoint = 1;
    for (var i = 0; i < amountOfSegments; i++) {
        print(startPoint + " " + segmentsEndPoints[i]);
        startPoint = segmentsEndPoints[i] + 1;
    }
}

var n = readline();
var pearls = readline().split(' ');

var counter = [];

var result = [];
var rLength = 0;

var i;
var start_idx = 0;

pearls.map(function(x, idx) {
    x = parseInt(x, 10);
    if(!counter[x]) {
        counter[x] = 1;
    } else {
        result[rLength] = [start_idx + 1, idx +1];
        start_idx = idx + 1;
        rLength = rLength + 1;
        counter = [];
    }
});

if (rLength == 0) {
    print("-1");
}
else {
    result[rLength-1][1] = parseInt(n, 10);

    print(rLength);
    for (i = 0; i < rLength; i++){
        print(result[i][0]+ ' ' + result[i][1]);
    }
}

var n = readline();
var pearls = readline().split(' ');

var counter = [];

var result = [];
var rLength = 0;

var i;
var start_idx = 0;

pearls.map(function(x, idx) {
    x = parseInt(x, 10);
    if(!counter[x]) {
        counter[x] = 1;
    } else {
        result[rLength] = [start_idx + 1, idx +1];
        start_idx = idx + 1;
        counter = [];
    }
});

if (rLength == 0) {
    print("-1\r\n");
}
else {
    result[rLength-1][1] = parseInt(n, 10);

    print("rLength\r\n");
    for (i = 0; i < rLength; i++){
        print("result[i][0] result[i][1]\n");
    }
}

var n = readline();
var pearls = readline().split(' ');

var counter = [];

var result = [];
var rLength = 0;

var i;
var start_idx = 0;

pearls.map(function(x, idx) {
    x = parseInt(x, 10);
    if(!counter[x]) {
        counter[x] = 1;
    } else {
        result[rLength] = [start_idx + 1, idx +1];
        start_idx = idx + 1;
        rLength = rLength + 1;
        counter = [];
    }
});

if (rLength == 0) {
    print("-1\r\n");
}
else {
    result[rLength-1][1] = parseInt(n, 10);

    print("rLength\r\n");
    for (i = 0; i < rLength; i++){
        print("result[i][0] result[i][1]\n");
    }
}

/*
 #include <stdio.h>
 int main(void) {
 int i;
 int start_idx = 0;

 scanf("%d", &n);

 for (i = 0; i < n; i++) {
 scanf("%d", &pearls[i]);

 if (increase_count(pearls[i]) == 0) {
 insert_new_pearl(pearls[i]);
 }
 else { // 2개가 되는 순간임
 result[result_length][0] = start_idx + 1;
 result[result_length++][1] = i + 1;
 start_idx = i + 1;
 length = 0;
 }
 }

 result[result_length-1][1] = n;

 if (result_length == 0) {
 printf("-1\n");
 }
 else {
 printf("%d\n", result_length);

 for (i = 0; i < result_length; i++){
 printf("%d %d\n", result[i][0], result[i][1]);
 }
 }

 return 0;
 }
 */


A matrix of size $$$n \times m$$$ is called nice, if all rows and columns of the matrix are palindromes. A sequence of integers $$$(a_1, a_2, \dots , a_k)$$$ is a palindrome, if for any integer $$$i$$$ ($$$1 \le i \le k$$$) the equality $$$a_i = a_{k - i + 1}$$$ holds.Sasha owns a matrix $$$a$$$ of size $$$n \times m$$$. In one operation he can increase or decrease any number in the matrix by one. Sasha wants to make the matrix nice. He is interested what is the minimum number of operations he needs.Help him!

The first line contains a single integer $$$t$$$ — the number of test cases ($$$1 \le t \le 10$$$). The $$$t$$$ tests follow. The first line of each test contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 100$$$) — the size of the matrix. Each of the next $$$n$$$ lines contains $$$m$$$ integers $$$a_{i, j}$$$ ($$$0 \le a_{i, j} \le 10^9$$$) — the elements of the matrix.

For each test output the smallest number of operations required to make the matrix nice.

NoteIn the first test case we can, for example, obtain the following nice matrix in $$$8$$$ operations:2 24 44 42 2In the second test case we can, for example, obtain the following nice matrix in $$$42$$$ operations:5 6 6 56 6 6 65 6 6 5

function i(v) {
        return parseInt(v);
}

function f(v) {
        return parseFloat(v);
}

function cmp(a, b) {
        return a - b > 0 ? -1 : 1;
}

function mp(v) {
        return parseInt(v);
}

var n = i(readline());

while(n--) {
        var a = readline().split(' ').map(mp);
        var arr = [];
        var ans = 0;
        for(var i = 0; i < a[0]; i++) {
                var line = readline().split(' ').map(mp);
                arr.push(line);
        }
        var m = parseInt((a[0] + 1) / 2)
        for(var i = 0; i < m; i++) {
                var l = 0, r = a[1] - 1;
                while(l <= r) {

                        var x = arr[i][l];
                        var y = arr[i][r];
                        var z = arr[a[0] - i - 1][l];
                        var w = arr[a[0] - i - 1][r];
                        var sr = [x, y, z, w];
                        sr.sort(mp)
                        add = Math.min(Math.abs(sr[0] - sr[1]) + Math.abs(sr[2] - sr[1]) + Math.abs(sr[3] - sr[1]),
                                Math.abs(sr[0] - sr[2]) + Math.abs(sr[1] - sr[2]) + Math.abs(sr[3] - sr[2])
                                ,Math.abs(sr[1] - sr[0]) + Math.abs(sr[2] - sr[0]) + Math.abs(sr[3] - sr[0])
                                ,Math.abs(sr[0] - sr[3]) + Math.abs(sr[1] - sr[3]) + Math.abs(sr[2] - sr[3]));

                        if(l == r || (i + 1 == m && a[0] % 2)) ans += parseInt(add / 2)
                        else ans += add
                        l++, r--;
                }
        }
        print(ans);
}

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}
function pow(base, n) {
  if (n === 0) return 1;
  let p = pow(base, Math.floor(n / 2));
  let res = mul(mod(p), mod(p));
  if (n % 2 === 1) res = mul(mod(res), base);
  return res;
}
function highestOneBit(i) {
  i |= i >> 1;
  i |= i >> 2;
  i |= i >> 4;
  i |= i >> 8;
  i |= i >> 16;
  return i - (i >>> 1);
}
function permutation(arr, len, store = "", permutations = []) {
  if (store.length === len) {
    permutations.push(store);
    return;
  }
  for (let i = 0; i < arr.length; i++) {
    const newArr = [...arr];
    const newChar = newArr.splice(i, 1);
    permutation(newArr, len, store.concat(newChar), permutations);
  }
  return permutations;
}

function main() {
  let t = +readLine();
  while (t--) {
    const [_row, _col] = readLine()
      .split(" ")
      .map((n) => parseInt(n));
    const arr = [];
    for (let i = 0; i < _row; i++) {
      const r = readLine()
        .split(" ")
        .map((n) => parseInt(n));
      arr.push(r);
    }

    let count = 0;

    for (let row = 0; row < _row; row++) {
      for (let col = 0; col < _col / 2; col++) {
        let nums = [arr[row][col], arr[_row - 1 - row][col], arr[row][_col - 1 - col]];
        nums.sort((a, b) => a - b);
        const target = nums[1];
        count += Math.abs(target - nums[0]) + Math.abs(target - nums[1]) + Math.abs(target - nums[2]);
        [arr[row][col], arr[_row - 1 - row][col], arr[row][_col - 1 - col]] = [target, target, target];
      }
    }
    console.log(count);
  }
}

function For(a, b, fn) {
  if (!fn) return For(0, a - 1, b);
  let res;
  for (let i = a; i <= b; i++) {
    if ((res = fn(i)) != null) return res;
  }
}
function ForR(a, b, fn) {
  if (!fn) return ForR(a - 1, 0, b);
  let res;
  for (let i = a; i >= b; i--) {
    if ((res = fn(i)) != null) return res;
  }
}

function Arr(a, b, fn) {
  if (typeof (b) == 'function') return Arr(0, a - 1, b);
  if (b < a) return [];
  let arr = Array(b - a + 1)
  for (let i = a; i <= b; i++) arr[i] = fn(i, arr);
  return arr;
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn ? fn(v) : v).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = 1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x < min) { min = x; index = i }
  }
  return [this[index], index, min];
}
Array.prototype.max = function (fn) {
  let max = -1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x > max) { max = x; index = i }
  }
  return [this[index], index, max];
}
Array.prototype.rev = function (first, last) {
  for (let i = first; i < (first + last) / 2; i++) {
    [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]
  }
}
Array.prototype.set = function (pos, arr) {
  for (let i = pos; i < pos + arr.length; i++) {
    this[i] = arr[i - pos];
  }
}
Array.prototype.for = function (a, b, fn) {
  let res
  for (let i = a; i <= b; i++) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.forR = function (a, b, fn) {
  let res
  for (let i = a; i >= b; i--) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.bin = function (comp, a, b) {
  let mid;
  while (a < b) {
    mid = (a + b) / 2 | 0;
    if (typeof comp == 'function' ? comp(this[mid]) : this[mid] < comp) a = mid + 1;
    else b = mid;
  }
  return a;
}
Array.prototype.cut = function (fn, a, b) {
  let arr = [];
  let sub = [];
  a = a || 0;
  b = b || (this.length - 1);
  for (let i = a; i <= b; i++) {
    sub.push(this[i])
    if (fn(this[i], i, this)) {
      arr.push(sub);
      sub = [];
    }
  }
  return arr;
}

function gcd(a, b) {
  while (b) [a, b] = [b, a % b];
  return a;
}
function mul(a, b, m) {
  return ((a >> 16) * b % m * 65536 + (a & 65535) * b) % m
}
function pow(a, n, m) {
  let r = 1;
  while (n) n & 1 ? (r = mul(r, a, m), n--) : [a, n] = [mul(a, a, m), n >> 1]
  return r;
}
let MOD = 998244353
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = a / b | 0, a -= t * b, u -= t * v, t = a, a = b, b = t, t = u, u = v);
  return (u + MOD) % MOD;
}

// let gt = Arr(n, (i, a) => i == 0 ? 1 : mul(a[i - 1], i, MOD));
// let rgt = Arr(n, (i, a) => i <= 1 ? 1 : MOD - mul((MOD / i | 0), a[998244353 % i], MOD));
// For(2, n - 1, i => { rgt[i] = mul(rgt[i], rgt[i - 1], MOD) });
// let nCk = (n, k) => mul(mul(gt[n], rgt[k], MOD), rgt[n - k], MOD);

// for (i = pos; i <= n; i += i & -i) fen[i]++; // start from index 1
// for (i = pos; i; i -= i & -i) ans += fen[i];

// let p = [2];
// for (let i = 3; i < 1e5; i += 2) {
//   let j, x = Math.sqrt(i);
//   for (j = 0; p[j] <= x; j++) if (i % p[j] == 0) break;
//   if (i % p[j] != 0) p.push(i);
// }

// let root = x => par[x] < 0 ? x : (par[x] = root(par[x]));
// let dsu = (x, y) => {
//   if ((x = root(x)) == (y = root(y))) return;
//   if (par[y] < par[x]) [x, y] = [y, x];
//   par[x] += par[y];
//   par[y] = x;
// }

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
function main() {
  let inp = input.split(/\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;
  let t = $()
  while (t--) {
    let [n, m] = $(2), res = 0
    let a = Arr(n, i => $(m))
    // log(a)
    For((n + 1) / 2 | 0, i => {
      For((m + 1) / 2 | 0, j => {
        let a1 = a[i][j], a2 = a[n - 1 - i][j], a3 = a[i][m - 1 - j], a4 = a[n - 1 - i][m - 1 - j];
        let s = min(
          abs(a2-a1)+abs(a3-a1)+abs(a4-a1),
          abs(a1-a2)+abs(a3-a2)+abs(a4-a2),
          abs(a1-a3)+abs(a2-a3)+abs(a4-a3),
          abs(a1-a4)+abs(a2-a4)+abs(a3-a4),
        )
        if (i == n - 1 - i) s /= 2;
        if (j == m - 1 - j) s /= 2;
        res += s;
      })
    })
    log(res)
  }
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    B();
});

function readline() {
    return inputString[currentLine++];
}

function pi(a) {
    return parseInt(a);
}

function ti(a){
    for(let i = 0; i < a.length; i++)
        a[i] = pi(a[i]);

    return a;
}

function B(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let [n,m] = ti(readline().split(' '));
        let mat = new Array(n);
        for(let i = 0; i < n; i++){
            mat[i] = ti(readline().split(' '));
        }

        let count = 0;
        for(let i = 0; i < n/2; i++){
            for(let j = 0; j < m/2; j++){
                let a = [];
                if(i !== n-i-1 && j !== m-j-1){
                    a = [mat[i][j], mat[i][m-j-1], mat[n-i-1][j], mat[n-i-1][m-j-1]];;
                }else{
                    a = [mat[i][j], mat[n-i-1][m-j-1]];
                }
                a.sort((a,b) => a-b);
                if(a.length === 4)
                    count += Math.abs(a[0]-a[1]) + Math.abs(a[1]-a[2]) + Math.abs(a[1]-a[3]);
                else
                    count += Math.abs(a[0]-a[1]);
            }
        }

        console.log(count);
    }
}

'use strict'
function solv() {
    var ip = readline().split(' ').map(x => parseInt(x));
    var x = ip[0];
    var y = ip[1];
    var grid = new Array(x);
    for (var n = 0; n < x; n++) {
        grid[n] = readline().split(' ').map(x => parseInt(x));
    }
    var res = 0;
    for (var n = 0; n < x; n++) {
        for (var k = 0; k < y; k++) {
            var a = grid[n][k];
            var b = grid[x - 1 - n][k];
            var c = grid[n][y - 1 - k];
            var d = grid[x - 1 - n][y - 1 - k];
            var tm = [a, b, c, d];
            tm.sort((x, y) => { return x > y });
            var md = tm[3] - tm[0] + tm[2] - tm[1]
            res += md
            /**/
        }
    }

    print(Math.floor(res / 4))
}

var tc = parseInt(readline())
while (tc--) solv()

function i(v) {
        return parseInt(v);
}

function f(v) {
        return parseFloat(v);
}

function cmp(a, b) {
        return a - b > 0 ? 1 : -1;
}

function mp(v) {
        return parseInt(v);
}

var n = i(readline());

while(n--) {
        var a = readline().split(' ').map(mp);
        var arr = [];
        var ans = 0;
        for(var i = 0; i < a[0]; i++) {
                var line = readline().split(' ').map(mp);
                arr.push(line);
        }
        var m = parseInt((a[0] + 1) / 2)
        for(var i = 0; i < m; i++) {
                var l = 0, r = a[1] - 1;
                while(l <= r) {
                        var obj = {};
                        var x = arr[i][l];
                        var y = arr[i][r];
                        var z = arr[a[0] - i - 1][l];
                        var w = arr[a[0] - i - 1][r];
                        var toSort = [x, y, z, w];
                        obj[x] = (obj[x] ? obj[x] + 1 : 1);
                        obj[y] = (obj[y] ? obj[y] + 1 : 1);
                        obj[z] = (obj[z] ? obj[z] + 1 : 1);
                        obj[w] = (obj[w] ? obj[w] + 1 : 1);
                        if(obj[x] == 1 && obj[y] == 1 && obj[z] == 1 && obj[w] == 1) {
                                toSort.sort(cmp);
                                add = Math.min(-toSort[0] + toSort[2] + toSort[3] - toSort[1],
                                -toSort[0] - toSort[1] + toSort[2] + toSort[3]);
                        }else {
                                if(obj[x] != 1) {
                                        add = Math.abs(y - x) + Math.abs(z - x) + Math.abs(w - x);
                                }else if(obj[y] != 1) {
                                        add = Math.abs(x - y) + Math.abs(z - y) + Math.abs(w - y);
                                }else {
                                        add = Math.abs(x - z) + Math.abs(y - z) + Math.abs(w - z);
                                }
                        }

                        if(l == r || (i + 1 == m && a[0] % 2)) ans += parseInt(add / 2)
                        else ans += add
                        l++, r--;
                }
        }
        print(ans);
}

function i(v) {
        return parseInt(v);
}

function f(v) {
        return parseFloat(v);
}

function cmp(a, b) {
        return a - b > 0 ? 1 : -1;
}

function mp(v) {
        return parseInt(v);
}

var n = i(readline());

while(n--) {
        var a, b = readline().split(' ').map(mp);
        var arr = [];
        for(var i = 0; i < a; a++) {
                var line = readline().split(' ').map(mp);
                arr.push(line);
        }

        print(arr);
}

function i(v) {
        return parseInt(v);
}

function f(v) {
        return parseFloat(v);
}

function cmp(a, b) {
        return a - b > 0 ? 1 : -1;
}

function mp(v) {
        return parseInt(v);
}

var n = i(readline());
n = 1
while(n--) {
        var a = readline().split(' ').map(mp);
        var arr = [];
        var ans = 0;
        for(var i = 0; i < a[0]; i++) {
                var line = readline().split(' ').map(mp);
                arr.push(line);
        }

        for(var i = 0; i < a[0] / 2; i++) {
                var l = 0, r = a[1] - 1;
                while(l < r) {
                        var obj = {};
                        var x = arr[i][l];
                        var y = arr[i][r];
                        var z = arr[a[0] - i - 1][l];
                        var w = arr[a[0] - i - 1][r];
                        var toSort = [x, y, z, w];
                        obj[x] = (obj[x] ? obj[x] + 1 : 1);
                        obj[y] = (obj[y] ? obj[y] + 1 : 1);
                        obj[z] = (obj[z] ? obj[z] + 1 : 1);
                        obj[w] = (obj[w] ? obj[w] + 1 : 1);
                        if(obj[x] == 1 && obj[y] == 1 && obj[z] == 1 && obj[w] == 1) {
                                toSort.sort(cmp);
                                ans += Math.min(-toSort[0] + toSort[2] + toSort[3] - toSort[1],
                                -toSort[0] - toSort[1] + toSort[2] + toSort[3]);
                        }else {
                                if(obj[x] != 1) {
                                        ans += Math.abs(y - x) + Math.abs(z - x) + Math.abs(w - x);
                                }else if(obj[y] != 1) {
                                        ans += Math.abs(x - y) + Math.abs(z - y) + Math.abs(w - y);
                                }else {
                                        ans += Math.abs(x - z) + Math.abs(y - z) + Math.abs(w - z);
                                }
                        }
                        l++, r--;
                        print(ans)
                }
        }
        print(ans); // odd rows cols not handel yet xD
}

function i(v) {
        return parseInt(v);
}

function f(v) {
        return parseFloat(v);
}

function cmp(a, b) {
        return a - b > 0 ? 1 : -1;
}

function mp(v) {
        return parseInt(v);
}

var n = i(readline());

while(n--) {
        var a = readline().split(' ').map(mp);
        var arr = [];
        for(var i = 0; i < a[0]; i++) {
                var line = readline().split(' ').map(mp);
                arr.push(line)
        }

        print(arr[0]);
}

function i(v) {
        return parseInt(v);
}

function f(v) {
        return parseFloat(v);
}

function cmp(a, b) {
        return a - b > 0 ? 1 : -1;
}

function mp(v) {
        return parseInt(v);
}

var n = i(readline());
n = 1
while(n--) {
        var a = readline().split(' ').map(mp);
        var arr = [];
        var ans = 0;
        for(var i = 0; i < a[0]; i++) {
                var line = readline().split(' ').map(mp);
                arr.push(line);
        }

        for(var i = 0; i < a[0]; i++) {
                var l = 0, r = a[1] - 1;
                while(l < r) {
                        var obj = {};
                        var x = arr[i][l];
                        var y = arr[i][r];
                        var z = arr[a[0] - i - 1][l];
                        var w = arr[a[0] - i - 1][r];
                        var toSort = [x, y, z, w];
                        obj[x] = (obj[x] ? obj[x] + 1 : 1);
                        obj[y] = (obj[y] ? obj[y] + 1 : 1);
                        obj[z] = (obj[z] ? obj[z] + 1 : 1);
                        obj[w] = (obj[w] ? obj[w] + 1 : 1);
                        if(obj[x] == 1 && obj[y] == 1 && obj[z] == 1 && obj[w] == 1) {
                                toSort.sort(cmp);
                                ans += Math.min(-toSort[0] + toSort[2] + toSort[3] - toSort[1],
                                -toSort[0] - toSort[1] + toSort[2] + toSort[3]);
                        }else {
                                if(obj[x] != 1) {
                                        ans += Math.abs(y - x) + Math.abs(z - x) + Math.abs(w - x);
                                }else if(obj[y] != 1) {
                                        ans += Math.abs(x - y) + Math.abs(z - y) + Math.abs(w - y);
                                }else {
                                        ans += Math.abs(x - z) + Math.abs(y - z) + Math.abs(w - z);
                                }
                        }
                        l++, r--;
                        print(ans)
                }
        }
        print(ans); // odd rows cols not handel yet xD
}

function i(v) {
        return parseInt(v);
}

function f(v) {
        return parseFloat(v);
}

function cmp(a, b) {
        return a - b > 0 ? 1 : -1;
}

function mp(v) {
        return parseInt(v);
}

var n = i(readline());

while(n--) {
        var a = readline().split(' ').map(mp);
        var arr = [];
        for(var i = 0; i < a[0]; i++) {
                var line = readline().split(' ').map(mp);
                arr.push(line)
        }

        print(arr);
}

function i(v) {
        return parseInt(v);
}

function f(v) {
        return parseFloat(v);
}

function cmp(a, b) {
        return a - b > 0 ? 1 : -1;
}

function mp(v) {
        return parseInt(v);
}

var n = i(readline());

while(n--) {
        var a = readline().split(' ').map(mp);
        var arr = [];
        var ans = 0;
        for(var i = 0; i < a[0]; i++) {
                var line = readline().split(' ').map(mp);
                arr.push(line);
        }
        var m = parseInt((a[0] + 1) / 2)
        for(var i = 0; i < m; i++) {
                var l = 0, r = a[1] - 1;
                while(l <= r) {
                        var obj = {};
                        var x = arr[i][l];
                        var y = arr[i][r];
                        var z = arr[a[0] - i - 1][l];
                        var w = arr[a[0] - i - 1][r];
                        var toSort = [x, y, z, w];
                        obj[x] = (obj[x] ? obj[x] + 1 : 1);
                        obj[y] = (obj[y] ? obj[y] + 1 : 1);
                        obj[z] = (obj[z] ? obj[z] + 1 : 1);
                        obj[w] = (obj[w] ? obj[w] + 1 : 1);
                        if(obj[x] == 1 && obj[y] == 1 && obj[z] == 1 && obj[w] == 1) {
                                toSort.sort(cmp);
                                ans += Math.min(-toSort[0] + toSort[2] + toSort[3] - toSort[1],
                                -toSort[0] - toSort[1] + toSort[2] + toSort[3]);
                        }else {
                                if(obj[x] != 1) {
                                        ans += Math.abs(y - x) + Math.abs(z - x) + Math.abs(w - x);
                                }else if(obj[y] != 1) {
                                        ans += Math.abs(x - y) + Math.abs(z - y) + Math.abs(w - y);
                                }else {
                                        ans += Math.abs(x - z) + Math.abs(y - z) + Math.abs(w - z);
                                }
                        }
                        l++, r--;
                }
        }
        print(ans);
}

function i(v) {
        return parseInt(v);
}

function f(v) {
        return parseFloat(v);
}

function cmp(a, b) {
        return a - b > 0 ? 1 : -1;
}

function mp(v) {
        return parseInt(v);
}

var n = i(readline());

while(n--) {
        var a, b = readline().split(' ').map(mp);
        var arr = [];
        print(a, b)
        for(var i = 0; i < a; i++) {
                var line = readline().split(' ').map(mp);
                arr.push(line[0]);
        }

        print(arr);
}

function i(v) {
        return parseInt(v);
}

function f(v) {
        return parseFloat(v);
}

function cmp(a, b) {
        return a - b > 0 ? 1 : -1;
}

function mp(v) {
        return parseInt(v);
}

var n = i(readline());

while(n--) {
        var a = readline().split(' ').map(mp);
        var arr = [];
        var ans = 0;
        for(var i = 0; i < a[0]; i++) {
                var line = readline().split(' ').map(mp);
                arr.push(line);
        }

        for(var i = 0; i < a[0]; i++) {
                var l = 0, r = a[1] - 1;
                while(l < r) {
                        var obj = {};
                        var x = arr[i][l];
                        var y = arr[i][r];
                        var z = arr[a[0] - i - 1][l];
                        var w = arr[a[0] - i - 1][r];
                        var toSort = [x, y, z, w];
                        obj[x] = (obj[x] ? obj[x] + 1 : 1);
                        obj[y] = (obj[y] ? obj[y] + 1 : 1);
                        obj[z] = (obj[z] ? obj[z] + 1 : 1);
                        obj[w] = (obj[w] ? obj[w] + 1 : 1);
                        if(obj[x] == 1 && obj[y] == 1 && obj[z] == 1 && obj[w] == 1) {
                                toSort.sort(cmp);
                                ans += Math.min(-toSort[0] + toSort[2] + toSort[3] - toSort[1],
                                -toSort[0] - toSort[1] + toSort[2] + toSort[3]);
                        }else {
                                if(obj[x] != 1) {
                                        ans += Math.abs(y - x) + Math.abs(z - x) + Math.abs(w - x);
                                }else if(obj[y] != 1) {
                                        ans += Math.abs(x - y) + Math.abs(z - y) + Math.abs(w - y);
                                }else {
                                        ans += Math.abs(x - z) + Math.abs(y - z) + Math.abs(w - z);
                                }
                        }
                        l++, r--;
                        print(ans); // odd rows cols not handel yet xD
                }
        }
}

function i(v) {
        return parseInt(v);
}

function f(v) {
        return parseFloat(v);
}

function cmp(a, b) {
        return a - b > 0 ? 1 : -1;
}

function mp(v) {
        return parseInt(v);
}

var n = i(readline());

while(n--) {
        var a, b = readline().split(' ').map(mp);
        var arr = [];
        print(n)
        for(var i = 0; i < a; i++) {
                var line = readline().split(' ').map(mp);
                arr.push(line[0]);
        }

        print(arr);
}

function i(v) {
        return parseInt(v);
}

function f(v) {
        return parseFloat(v);
}

function cmp(a, b) {
        return a - b > 0 ? 1 : -1;
}

function mp(v) {
        return parseInt(v);
}

var n = i(readline());
n = 1
while(n--) {
        var a = readline().split(' ').map(mp);
        var arr = [];
        var ans = 0;
        for(var i = 0; i < a[0]; i++) {
                var line = readline().split(' ').map(mp);
                arr.push(line);
        }

        for(var i = 0; i < (a[0] + 1) / 2; i++) {
                print(i)
                var l = 0, r = a[1] - 1;
                while(l <= r) {
                        var obj = {};
                        var x = arr[i][l];
                        var y = arr[i][r];
                        var z = arr[a[0] - i - 1][l];
                        var w = arr[a[0] - i - 1][r];
                        var toSort = [x, y, z, w];
                        obj[x] = (obj[x] ? obj[x] + 1 : 1);
                        obj[y] = (obj[y] ? obj[y] + 1 : 1);
                        obj[z] = (obj[z] ? obj[z] + 1 : 1);
                        obj[w] = (obj[w] ? obj[w] + 1 : 1);
                        if(obj[x] == 1 && obj[y] == 1 && obj[z] == 1 && obj[w] == 1) {
                                toSort.sort(cmp);
                                ans += Math.min(-toSort[0] + toSort[2] + toSort[3] - toSort[1],
                                -toSort[0] - toSort[1] + toSort[2] + toSort[3]);
                        }else {
                                if(obj[x] != 1) {
                                        ans += Math.abs(y - x) + Math.abs(z - x) + Math.abs(w - x);
                                }else if(obj[y] != 1) {
                                        ans += Math.abs(x - y) + Math.abs(z - y) + Math.abs(w - y);
                                }else {
                                        ans += Math.abs(x - z) + Math.abs(y - z) + Math.abs(w - z);
                                }
                        }
                        l++, r--;
                }
        }
        print(ans);
}

function i(v) {
        return parseInt(v);
}

function f(v) {
        return parseFloat(v);
}

function cmp(a, b) {
        return a - b > 0 ? 1 : -1;
}

function mp(v) {
        return parseInt(v);
}

var n = i(readline());

while(n--) {
        var a = readline().split(' ').map(mp);
        var arr = [];
        var ans = 0;
        for(var i = 0; i < a[0]; i++) {
                var line = readline().split(' ').map(mp);
                arr.push(line);
        }

        for(var i = 0; i < a[0]; i++) {
                var l = 0, r = a[1] - 1;
                while(l < r) {
                        var obj = {};
                        var x = arr[i][l];
                        var y = arr[i][r];
                        var z = arr[a[0] - i - 1][l];
                        var w = arr[a[0] - i - 1][r];
                        var toSort = [x, y, z, w];
                        obj[x] = (obj[x] ? obj[x] + 1 : 1);
                        obj[y] = (obj[y] ? obj[y] + 1 : 1);
                        obj[z] = (obj[z] ? obj[z] + 1 : 1);
                        obj[w] = (obj[w] ? obj[w] + 1 : 1);
                        if(obj[x] == 1 && obj[y] == 1 && obj[z] == 1 && obj[w] == 1) {
                                toSort.sort(cmp);
                                ans += Math.min(-toSort[0] + toSort[2] + toSort[3] - toSort[1],
                                -toSort[0] - toSort[1] + toSort[2] + toSort[3]);
                        }else {
                                if(obj[x] != 1) {
                                        ans += Math.abs(y - x) + Math.abs(z - x) + Math.abs(w - x);
                                }else if(obj[y] != 1) {
                                        ans += Math.abs(x - y) + Math.abs(z - y) + Math.abs(w - y);
                                }else {
                                        ans += Math.abs(x - z) + Math.abs(y - z) + Math.abs(w - z);
                                }
                        }
                        l++, r--;

                }print(ans); // odd rows cols not handel yet xD
        }
}

function i(v) {
        return parseInt(v);
}

function f(v) {
        return parseFloat(v);
}

function cmp(a, b) {
        return a - b > 0 ? -1 : 1;
}

function mp(v) {
        return parseInt(v);
}

var n = i(readline());

while(n--) {
        var a = readline().split(' ').map(mp);
        var arr = [];
        var ans = 0;
        for(var i = 0; i < a[0]; i++) {
                var line = readline().split(' ').map(mp);
                arr.push(line);
        }
        var m = parseInt((a[0] + 1) / 2)
        for(var i = 0; i < m; i++) {
                var l = 0, r = a[1] - 1;
                while(l <= r) {

                        var x = arr[i][l];
                        var y = arr[i][r];
                        var z = arr[a[0] - i - 1][l];
                        var w = arr[a[0] - i - 1][r];
                        var sr = [x, y, z, w];
                        sr.sort(mp)
                        add = Math.min(Math.abs(sr[0] - sr[1]) + Math.abs(sr[2] - sr[1]) + Math.abs(sr[3] - sr[1]),
                                Math.abs(sr[0] - sr[2]) + Math.abs(sr[1] - sr[2]) + Math.abs(sr[3] - sr[2]));

                        if(l == r || (i + 1 == m && a[0] % 2)) ans += parseInt(add / 2)
                        else ans += add
                        l++, r--;
                }
        }
        print(ans);
}

function i(v) {
        return parseInt(v);
}

function f(v) {
        return parseFloat(v);
}

function cmp(a, b) {
        return a - b > 0 ? 1 : -1;
}

function mp(v) {
        return parseInt(v);
}

var n = i(readline());

while(n--) {
        var a, b = readline().split(' ').map(mp);
        var arr = [];
        for(var i = 0; i < a; i++) {
                var line = readline().split(' ').map(mp);
                arr.push(line);
        }

        print(arr);
}

function i(v) {
        return parseInt(v);
}

function f(v) {
        return parseFloat(v);
}

function cmp(a, b) {
        return a - b > 0 ? -1 : 1;
}

function mp(v) {
        return parseInt(v);
}

var n = i(readline());

while(n--) {
        var a = readline().split(' ').map(mp);
        var arr = [];
        var ans = 0;
        for(var i = 0; i < a[0]; i++) {
                var line = readline().split(' ').map(mp);
                arr.push(line);
        }
        var m = parseInt((a[0] + 1) / 2)
        for(var i = 0; i < m; i++) {
                var l = 0, r = a[1] - 1;
                while(l <= r) {
                        var obj = {};
                        var x = arr[i][l];
                        var y = arr[i][r];
                        var z = arr[a[0] - i - 1][l];
                        var w = arr[a[0] - i - 1][r];
                        var toSort = [x, y, z, w];
                        toSort.sort(mp)

                                add = Math.min(-toSort[0] + toSort[2] + toSort[3] - toSort[1],
                                -toSort[0] - toSort[1] + toSort[2] + toSort[3]);

                        if(l == r || (i + 1 == m && a[0] % 2)) ans += parseInt(add / 2)
                        else ans += add
                        l++, r--;
                }
        }
        print(ans);
}

function i(v) {
        return parseInt(v);
}

function f(v) {
        return parseFloat(v);
}

function cmp(a, b) {
        return a - b > 0 ? 1 : -1;
}

function mp(v) {
        return parseInt(v);
}

var n = i(readline());

while(n--) {
        var a, b = readline().split(' ').map(mp);
        var arr = [];
        for(var i = 0; i < a; a++) {
                var line = readline().split(' ').map(mp);
                arr.push(line);
                print(line)
        }

        print(arr);
}

function i(v) {
        return parseInt(v);
}

function f(v) {
        return parseFloat(v);
}

function cmp(a, b) {
        return a - b > 0 ? 1 : -1;
}

function mp(v) {
        return parseInt(v);
}

var n = i(readline());

while(n--) {
        var a = readline().split(' ').map(mp);
        var arr = [];
        var ans = 0;
        for(var i = 0; i < a[0]; i++) {
                var line = readline().split(' ').map(mp);
                arr.push(line);
        }
        var m = parseInt((a[0] + 1) / 2)
        for(var i = 0; i < m; i++) {
                var l = 0, r = a[1] - 1;
                while(l <= r) {

                        var x = arr[i][l];
                        var y = arr[i][r];
                        var z = arr[a[0] - i - 1][l];
                        var w = arr[a[0] - i - 1][r];
                        var sr = [x, y, z, w];

                        add = Math.min(Math.abs(sr[0] - sr[1]) + Math.abs(sr[2] - sr[1]) + Math.abs(sr[3] - sr[1]),
                                Math.abs(sr[0] - sr[2]) + Math.abs(sr[1] - sr[2]) + Math.abs(sr[3] - sr[2]));

                        if(l == r || (i + 1 == m && a[0] % 2)) ans += parseInt(add / 2)
                        else ans += add
                        l++, r--;
                }
        }
        print(ans);
}

function i(v) {
        return parseInt(v);
}

function f(v) {
        return parseFloat(v);
}

function cmp(a, b) {
        return a - b > 0 ? 1 : -1;
}

function mp(v) {
        return parseInt(v);
}

var n = i(readline());

while(n--) {
        var a = readline().split(' ').map(mp);
        var arr = [];
        var ans = 0;
        for(var i = 0; i < a[0]; i++) {
                var line = readline().split(' ').map(mp);
                arr.push(line);
        }

        for(var i = 0; i < (a[0] + 1) / 2; i++) {
                var l = 0, r = a[1] - 1;
                while(l <= r) {
                        var obj = {};
                        var x = arr[i][l];
                        var y = arr[i][r];
                        var z = arr[a[0] - i - 1][l];
                        var w = arr[a[0] - i - 1][r];
                        var toSort = [x, y, z, w];
                        obj[x] = (obj[x] ? obj[x] + 1 : 1);
                        obj[y] = (obj[y] ? obj[y] + 1 : 1);
                        obj[z] = (obj[z] ? obj[z] + 1 : 1);
                        obj[w] = (obj[w] ? obj[w] + 1 : 1);
                        if(obj[x] == 1 && obj[y] == 1 && obj[z] == 1 && obj[w] == 1) {
                                toSort.sort(cmp);
                                ans += Math.min(-toSort[0] + toSort[2] + toSort[3] - toSort[1],
                                -toSort[0] - toSort[1] + toSort[2] + toSort[3]);
                        }else {
                                if(obj[x] != 1) {
                                        ans += Math.abs(y - x) + Math.abs(z - x) + Math.abs(w - x);
                                }else if(obj[y] != 1) {
                                        ans += Math.abs(x - y) + Math.abs(z - y) + Math.abs(w - y);
                                }else {
                                        ans += Math.abs(x - z) + Math.abs(y - z) + Math.abs(w - z);
                                }
                        }
                        l++, r--;
                }
        }
        print(ans);
}

function i(v) {
        return parseInt(v);
}

function f(v) {
        return parseFloat(v);
}

function cmp(a, b) {
        return a - b > 0 ? 1 : -1;
}

function mp(v) {
        return parseInt(v);
}

var n = i(readline());

while(n--) {
        var a = readline().split(' ').map(mp);
        var arr = [];
        var ans = 0;
        for(var i = 0; i < a[0]; i++) {
                var line = readline().split(' ').map(mp);
                arr.push(line);
        }

        for(var i = 0; i < a[0]; i++) {
                var l = 0, r = a[1] - 1;
                while(l < r) {
                        var obj = {};
                        var x = arr[i][l];
                        var y = arr[i][r];
                        var z = arr[a[0] - i - 1][l];
                        var w = arr[a[0] - i - 1][r];
                        var toSort = [x, y, z, w];
                        obj[x] = (obj[x] ? obj[x] + 1 : 1);
                        obj[y] = (obj[y] ? obj[y] + 1 : 1);
                        obj[z] = (obj[z] ? obj[z] + 1 : 1);
                        obj[w] = (obj[w] ? obj[w] + 1 : 1);
                        if(obj[x] == 1 && obj[y] == 1 && obj[z] == 1 && obj[w] == 1) {
                                toSort.sort(cmp);
                                ans += Math.min(-toSort[0] + toSort[2] + toSort[3] - toSort[1],
                                -toSort[0] - toSort[1] + toSort[2] + toSort[3]);
                        }else {
                                if(obj[x] != 1) {
                                        ans += Math.abs(y - x) + Math.abs(z - x) + Math.abs(w - x);
                                }else if(obj[y] != 1) {
                                        ans += Math.abs(x - y) + Math.abs(z - y) + Math.abs(w - y);
                                }else {
                                        ans += Math.abs(x - z) + Math.abs(y - z) + Math.abs(w - z);
                                }
                        }
                        l++, r--;

                }
        }
        print(ans); // odd rows cols not handel yet xD
}

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}
function pow(base, n) {
  if (n === 0) return 1;
  let p = pow(base, Math.floor(n / 2));
  let res = mul(mod(p), mod(p));
  if (n % 2 === 1) res = mul(mod(res), base);
  return res;
}
function highestOneBit(i) {
  i |= i >> 1;
  i |= i >> 2;
  i |= i >> 4;
  i |= i >> 8;
  i |= i >> 16;
  return i - (i >>> 1);
}
function permutation(arr, len, store = "", permutations = []) {
  if (store.length === len) {
    permutations.push(store);
    return;
  }
  for (let i = 0; i < arr.length; i++) {
    const newArr = [...arr];
    const newChar = newArr.splice(i, 1);
    permutation(newArr, len, store.concat(newChar), permutations);
  }
  return permutations;
}

function main() {
  let t = +readLine();
  while (t--) {
    const map = new Map();
    const [_row, _col] = readLine()
      .split(" ")
      .map((n) => parseInt(n));
    const arr = [];
    for (let i = 0; i < _row; i++) {
      const r = readLine()
        .split(" ")
        .map((n) => {
          n = parseInt(n);
          map.set(n, n);
          return n;
        });
      arr.push(r);
    }

    let min = Infinity;
    for (let [key, value] of map) {
      let count = 0;
      for (let row = 0; row < _row; row++) {
        for (let col = 0; col < _col; col++) {
          const diff = Math.abs(arr[row][col] - key);
          count += diff;
        }
      }
      min = Math.min(min, count);
    }

    console.log(min);
  }
}

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}
function pow(base, n) {
  if (n === 0) return 1;
  let p = pow(base, Math.floor(n / 2));
  let res = mul(mod(p), mod(p));
  if (n % 2 === 1) res = mul(mod(res), base);
  return res;
}
function highestOneBit(i) {
  i |= i >> 1;
  i |= i >> 2;
  i |= i >> 4;
  i |= i >> 8;
  i |= i >> 16;
  return i - (i >>> 1);
}
function permutation(arr, len, store = "", permutations = []) {
  if (store.length === len) {
    permutations.push(store);
    return;
  }
  for (let i = 0; i < arr.length; i++) {
    const newArr = [...arr];
    const newChar = newArr.splice(i, 1);
    permutation(newArr, len, store.concat(newChar), permutations);
  }
  return permutations;
}

function main() {
  let t = +readLine();
  while (t--) {
    const [_row, _col] = readLine()
      .split(" ")
      .map((n) => parseInt(n));
    const arr = [];
    for (let i = 0; i < _row; i++) {
      const r = readLine()
        .split(" ")
        .map((n) => parseInt(n));
      arr.push(r);
    }

    let count = 0;

    for (let row = 0; row < _row; row++) {
      for (let col = 0; col < Math.floor(_col / 2); col++) {
        let nums = [arr[row][col], arr[_row - 1 - row][col], arr[row][_col - 1 - col]];
        nums.sort((a, b) => a - b);
        const target = nums[1];
        count += Math.abs(target - nums[0]) + Math.abs(target - nums[1]) + Math.abs(target - nums[2]);
        [arr[row][col], arr[_row - 1 - row][col], arr[row][_col - 1 - col]] = [target, target, target];
      }
    }
    console.log(count);
  }
}

function For(a, b, fn) {
  if (!fn) return For(0, a - 1, b);
  let res;
  for (let i = a; i <= b; i++) {
    if ((res = fn(i)) != null) return res;
  }
}
function ForR(a, b, fn) {
  if (!fn) return ForR(a - 1, 0, b);
  let res;
  for (let i = a; i >= b; i--) {
    if ((res = fn(i)) != null) return res;
  }
}

function Arr(a, b, fn) {
  if (typeof (b) == 'function') return Arr(0, a - 1, b);
  if (b < a) return [];
  let arr = Array(b - a + 1)
  for (let i = a; i <= b; i++) arr[i] = fn(i, arr);
  return arr;
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn ? fn(v) : v).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = 1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x < min) { min = x; index = i }
  }
  return [this[index], index, min];
}
Array.prototype.max = function (fn) {
  let max = -1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x > max) { max = x; index = i }
  }
  return [this[index], index, max];
}
Array.prototype.rev = function (first, last) {
  for (let i = first; i < (first + last) / 2; i++) {
    [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]
  }
}
Array.prototype.set = function (pos, arr) {
  for (let i = pos; i < pos + arr.length; i++) {
    this[i] = arr[i - pos];
  }
}
Array.prototype.for = function (a, b, fn) {
  let res
  for (let i = a; i <= b; i++) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.forR = function (a, b, fn) {
  let res
  for (let i = a; i >= b; i--) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.bin = function (comp, a, b) {
  let mid;
  while (a < b) {
    mid = (a + b) / 2 | 0;
    if (typeof comp == 'function' ? comp(this[mid]) : this[mid] < comp) a = mid + 1;
    else b = mid;
  }
  return a;
}
Array.prototype.cut = function (fn, a, b) {
  let arr = [];
  let sub = [];
  a = a || 0;
  b = b || (this.length - 1);
  for (let i = a; i <= b; i++) {
    sub.push(this[i])
    if (fn(this[i], i, this)) {
      arr.push(sub);
      sub = [];
    }
  }
  return arr;
}

function gcd(a, b) {
  while (b) [a, b] = [b, a % b];
  return a;
}
function mul(a, b, m) {
  return ((a >> 16) * b % m * 65536 + (a & 65535) * b) % m
}
function pow(a, n, m) {
  let r = 1;
  while (n) n & 1 ? (r = mul(r, a, m), n--) : [a, n] = [mul(a, a, m), n >> 1]
  return r;
}
let MOD = 998244353
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = a / b | 0, a -= t * b, u -= t * v, t = a, a = b, b = t, t = u, u = v);
  return (u + MOD) % MOD;
}

// let gt = Arr(n, (i, a) => i == 0 ? 1 : mul(a[i - 1], i, MOD));
// let rgt = Arr(n, (i, a) => i <= 1 ? 1 : MOD - mul((MOD / i | 0), a[998244353 % i], MOD));
// For(2, n - 1, i => { rgt[i] = mul(rgt[i], rgt[i - 1], MOD) });
// let nCk = (n, k) => mul(mul(gt[n], rgt[k], MOD), rgt[n - k], MOD);

// for (i = pos; i <= n; i += i & -i) fen[i]++; // start from index 1
// for (i = pos; i; i -= i & -i) ans += fen[i];

// let p = [2];
// for (let i = 3; i < 1e5; i += 2) {
//   let j, x = Math.sqrt(i);
//   for (j = 0; p[j] <= x; j++) if (i % p[j] == 0) break;
//   if (i % p[j] != 0) p.push(i);
// }

// let root = x => par[x] < 0 ? x : (par[x] = root(par[x]));
// let dsu = (x, y) => {
//   if ((x = root(x)) == (y = root(y))) return;
//   if (par[y] < par[x]) [x, y] = [y, x];
//   par[x] += par[y];
//   par[y] = x;
// }

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
function main() {
  let inp = input.split(/\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;
  let t = $()
  while (t--) {
    let [n, m] = $(2), res = 0
    let a = Arr(n, i => $(m))
    // log(a)
    For((n + 1) / 2 | 0, i => {
      For((m + 1) / 2 | 0, j => {
        let a1 = a[i][j], a2 = a[n - 1 - i][j], a3 = a[i][m - 1 - j], a4 = a[n - 1 - i][m - 1 - j];
        // log(i, j, a1, a2, a3, a4)
        let tb = Math.round((a1 + a2 + a3 + a4) / 4)
        let s = abs(a1 - tb) + abs(a2 - tb) + abs(a3 - tb) + abs(a4 - tb);
        if (i == n - 1 - i || j == m - 1 - j) s /= 2;
        res += s;
      })
    })
    log(res)
  }
}

function i(v) {
        return parseInt(v);
}

function f(v) {
        return parseFloat(v);
}

function cmp(a, b) {
        return a - b > 0 ? 1 : -1;
}

function mp(v) {
        return parseInt(v);
}

var n = i(readline());

while(n--) {
        var a = readline().split(' ').map(mp);
        var arr = [];
        for(var i = 0; i < a[0]; i++) {
                var line = readline().split(' ').map(mp);
        }

        print(arr);
}

function i(v) {
        return parseInt(v);
}

function f(v) {
        return parseFloat(v);
}

function cmp(a, b) {
        return a - b > 0 ? 1 : -1;
}

function mp(v) {
        return parseInt(v);
}

var n = i(readline());

while(n--) {
        var a = readline().split(' ').map(mp);
        var arr = [];
        var ans = 0;
        for(var i = 0; i < a[0]; i++) {
                var line = readline().split(' ').map(mp);
                arr.push(line);
        }

        for(var i = 0; i < a[0]; i++) {
                var l = 0, r = a[1] - 1;
                while(l < r) {
                        var obj = {};
                        var x = arr[i][l];
                        var y = arr[i][r];
                        var z = arr[a[0] - i - 1][l];
                        var w = arr[a[0] - i - 1][r];
                        var toSort = [x, y, z, w];
                        obj[x] = (obj[x] ? obj[x] + 1 : 1);
                        obj[y] = (obj[y] ? obj[y] + 1 : 1);
                        obj[z] = (obj[z] ? obj[z] + 1 : 1);
                        obj[w] = (obj[w] ? obj[w] + 1 : 1);
                        if(obj[x] == 1 && obj[y] == 1 && obj[z] == 1 && obj[w] == 1) {
                                toSort.sort(cmp);
                                ans += Math.min(-toSort[0] + toSort[2] + toSort[3] - toSort[1],
                                -toSort[0] - toSort[1] + toSort[2] + toSort[3]);
                        }else {
                                if(obj[x] != 1) {
                                        ans += Math.abs(y - x) + Math.abs(z - x) + Math.abs(w - x);
                                }else if(obj[y] != 1) {
                                        ans += Math.abs(x - y) + Math.abs(z - y) + Math.abs(w - y);
                                }else {
                                        ans += Math.abs(x - z) + Math.abs(y - z) + Math.abs(w - z);
                                }
                        }
                        l++, r--;
                        print(ans)
                }
        }
        print(ans); // odd rows cols not handel yet xD
}

function i(v) {
        return parseInt(v);
}

function f(v) {
        return parseFloat(v);
}

function cmp(a, b) {
        return a - b > 0 ? 1 : -1;
}

function mp(v) {
        return parseInt(v);
}

var n = i(readline());

while(n--) {
        var a, b = readline().split(' ').map(mp);
        var arr = [];
        for(var i = 0; i < a; i++) {
                var line = readline().split(' ').map(mp);
                arr.push(line[0]);
        }

        print(arr);
}

function i(v) {
        return parseInt(v);
}

function f(v) {
        return parseFloat(v);
}

function cmp(a, b) {
        return a - b > 0 ? 1 : -1;
}

function mp(v) {
        return parseInt(v);
}

var n = i(readline());

while(n--) {
        var a = readline().split(' ').map(mp);
        var arr = [];
        var ans = 0;
        for(var i = 0; i < a[0]; i++) {
                var line = readline().split(' ').map(mp);
                arr.push(line);
        }
        var m = parseInt((a[0] + 1) / 2)
        for(var i = 0; i < m; i++) {
                var l = 0, r = a[1] - 1;
                while(l <= r) {
                        var obj = {};
                        var x = arr[i][l];
                        var y = arr[i][r];
                        var z = arr[a[0] - i - 1][l];
                        var w = arr[a[0] - i - 1][r];
                        var toSort = [x, y, z, w];

                                add = Math.min(-toSort[0] + toSort[2] + toSort[3] - toSort[1],
                                -toSort[0] - toSort[1] + toSort[2] + toSort[3]);

                        if(l == r || (i + 1 == m && a[0] % 2)) ans += parseInt(add / 2)
                        else ans += add
                        l++, r--;
                }
        }
        print(ans);
}

function i(v) {
        return parseInt(v);
}

function f(v) {
        return parseFloat(v);
}

function cmp(a, b) {
        return a - b > 0 ? 1 : -1;
}

function mp(v) {
        return parseInt(v);
}

var n = i(readline());

while(n--) {
        var a = readline().split(' ').map(mp);
        var arr = [];
        var ans = 0;
        for(var i = 0; i < a[0]; i++) {
                var line = readline().split(' ').map(mp);
                arr.push(line);
        }
        var m = parseInt((a[0] + 1) / 2)
        for(var i = 0; i < m; i++) {
                var l = 0, r = a[1] - 1;
                while(l <= r) {
                        var obj = {};
                        var x = arr[i][l];
                        var y = arr[i][r];
                        var z = arr[a[0] - i - 1][l];
                        var w = arr[a[0] - i - 1][r];
                        var toSort = [x, y, z, w];
                        obj[x] = (obj[x] ? obj[x] + 1 : 1);
                        obj[y] = (obj[y] ? obj[y] + 1 : 1);
                        obj[z] = (obj[z] ? obj[z] + 1 : 1);
                        obj[w] = (obj[w] ? obj[w] + 1 : 1);
                        if(obj[x] == 1 && obj[y] == 1 && obj[z] == 1 && obj[w] == 1) {
                                toSort.sort(cmp);
                                add = Math.min(-toSort[0] + toSort[2] + toSort[3] - toSort[1],
                                -toSort[0] - toSort[1] + toSort[2] + toSort[3]);
                        }else {
                                if(obj[x] != 1) {
                                        add = Math.abs(y - x) + Math.abs(z - x) + Math.abs(w - x);
                                }else if(obj[y] != 1) {
                                        add = Math.abs(x - y) + Math.abs(z - y) + Math.abs(w - y);
                                }else {
                                        add = Math.abs(x - z) + Math.abs(y - z) + Math.abs(w - z);
                                }
                        }

                        if(l == r || i + 1 == m) ans += parseInt(add / 2)
                        else ans += add
                        l++, r--;
                }
        }
        print(ans);
}

function i(v) {
        return parseInt(v);
}

function f(v) {
        return parseFloat(v);
}

function cmp(a, b) {
        return a - b > 0 ? 1 : -1;
}

function mp(v) {
        return parseInt(v);
}

var n = i(readline());

while(n--) {
        var a = readline().split(' ').map(mp);
        var arr = [];
        print(a)
        for(var i = 0; i < a[0]; i++) {
                var line = readline().split(' ').map(mp);
                arr.push(line[0]);
        }

        print(arr);
}

function i(v) {
        return parseInt(v);
}

function f(v) {
        return parseFloat(v);
}

function cmp(a, b) {
        return a - b > 0 ? 1 : -1;
}

function mp(v) {
        return parseInt(v);
}

var n = i(readline());

while(n--) {
        var a = readline().split(' ').map(mp);
        var arr = [];
        var ans = 0;
        for(var i = 0; i < a[0]; i++) {
                var line = readline().split(' ').map(mp);
                arr.push(line);
        }
        var m = parseInt((a[0] + 1) / 2)
        for(var i = 0; i < m; i++) {
                var l = 0, r = a[1] - 1;
                while(l <= r) {
                        var obj = {};
                        var x = arr[i][l];
                        var y = arr[i][r];
                        var z = arr[a[0] - i - 1][l];
                        var w = arr[a[0] - i - 1][r];
                        var toSort = [x, y, z, w];
                        toSort.sort(mp)
                                add = Math.min(-toSort[0] + toSort[2] + toSort[3] - toSort[1],
                                -toSort[0] - toSort[1] + toSort[2] + toSort[3]);

                        if(l == r || (i + 1 == m && a[0] % 2)) ans += parseInt(add / 2)
                        else ans += add
                        l++, r--;
                }
        }
        print(ans);
}


One morning the Cereal Guy found out that all his cereal flakes were gone. He found a note instead of them. It turned out that his smart roommate hid the flakes in one of n boxes. The boxes stand in one row, they are numbered from 1 to n from the left to the right. The roommate left hints like "Hidden to the left of the i-th box" ("To the left of i"), "Hidden to the right of the i-th box" ("To the right of i"). Such hints mean that there are no flakes in the i-th box as well. The Cereal Guy wants to know the minimal number of boxes he necessarily needs to check to find the flakes considering all the hints. Or he wants to find out that the hints are contradictory and the roommate lied to him, that is, no box has the flakes.

The first line contains two integers n and m (1 ≤ n ≤ 1000, 0 ≤ m ≤ 1000) which represent the number of boxes and the number of hints correspondingly. Next m lines contain hints like "To the left of i" and "To the right of i", where i is integer (1 ≤ i ≤ n). The hints may coincide.

The answer should contain exactly one integer — the number of boxes that should necessarily be checked or "-1" if the hints are contradictory.

'use strict'

let lll = readline().split(' ').map(v => parseInt(v))
let N = lll[0]
let ls = []
let rs = []
for (let i = 0; i < lll[1]; i++) {
  let ll = readline().split(' ')
  ;(ll[2] == 'left' ? ls : rs).push(+ll[ll.length - 1])
}

let bs = []

let n = N
while(n--) {
  bs.push(true)
}

ls = ls.sort((a, b) => a - b)
rs = rs.sort((a, b) => a - b)

let ml = ls.length ? ls[0] : N + 1
let mr = rs.length ? rs[rs.length - 1] : 0

let r = ml - mr - 1

print(r <= 0 ? -1 : r)

var getNums = function() {
	return readline().split(' ').map(function(a) {return parseInt(a)});
};

var input;
input = getNums();
var n1 = input[0];
var n2 = input[1];
var left = 1, right = n1;

for (var i = 0; i < n2; i++) {
	input = readline();
	var j;
	if (input.match(/To the left of/)) {
		j = parseInt(input.replace('To the left of ',''));
		right = Math.min(right, j - 1);
	} else {
		j = parseInt(input.replace('To the right of ',''));
		left = Math.max(left, j + 1);
	}
}

if (left > right) {
	print(-1);
} else {
	print(right - left + 1);
}


Note that this is the first problem of the two similar problems. You can hack this problem only if you solve both problems.You are given a tree with $$$n$$$ nodes. In the beginning, $$$0$$$ is written on all edges. In one operation, you can choose any $$$2$$$ distinct leaves $$$u$$$, $$$v$$$ and any real number $$$x$$$ and add $$$x$$$ to values written on all edges on the simple path between $$$u$$$ and $$$v$$$.For example, on the picture below you can see the result of applying two operations to the graph: adding $$$2$$$ on the path from $$$7$$$ to $$$6$$$, and then adding $$$-0.5$$$ on the path from $$$4$$$ to $$$5$$$.   Is it true that for any configuration of real numbers written on edges, we can achieve it with a finite number of operations?Leaf is a node of a tree of degree $$$1$$$. Simple path is a path that doesn't contain any node twice.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \neq v$$$), meaning that there is an edge between nodes $$$u$$$ and $$$v$$$. It is guaranteed that these edges form a tree.

If there is a configuration of real numbers written on edges of the tree that we can't achieve by performing the operations, output "NO".  Otherwise, output "YES".  You can print each letter in any case (upper or lower).

NoteIn the first example, we can add any real $$$x$$$ to the value written on the only edge $$$(1, 2)$$$.  In the second example, one of configurations that we can't reach is $$$0$$$ written on $$$(1, 2)$$$ and $$$1$$$ written on $$$(2, 3)$$$.  Below you can see graphs from examples $$$3$$$, $$$4$$$:

var n = +readline();
var arr = [];
for (var i = 0; i < n; i++) {
  arr[i] = 0;
}
for (var i = 1; i < n; i++) {
  var point = readline().split(' ').map(item => +item - 1);
  arr[point[0]]++;
  arr[point[1]]++;
}
print(arr.find(item => item === 2) ? 'NO' : 'YES');

"use strict";

// readline().split(' ').map(value => +value);
var n = +readline();
var A = new Array(Math.pow(10, 5) + 100).fill(0);
for (var i = 0; i < n - 1; ++i) {
    var input = readline().split(' ').map(value => +value);
    var u = input[0];
    var v = input[1];

    ++A[u];
    ++A[v];
}

var result = 'YES';
for (var i = 1; i <= n; ++i) {
    if (A[i] === 2) {
        result = 'NO';
        break;
    }
}

write(result);