const increase = a => {
  for (let i = 0; i < a.length; i++) {
    if (a[i] !== i + 1) return false;
  }
  return true;
};

const permutation = (n, a, tag) => {
  const b = [...a];
  if (tag === 0) {
    for (let j = 0; j < n; j++) {
      let w = b[2 * j];
      b[2 * j] = b[2 * j + 1];
      b[2 * j + 1] = w;
    }
  } else if (tag === 1) {
    for (let j = 0; j < n; j++) {
      let w = b[j];
      b[j] = b[n + j];
      b[n + j] = w;
    }
  }
  return b;
};

const solve = (n, a) => {
  if (increase(a)) return 0;

  let p1 = [...a];
  let t1 = 0;
  let p2 = [...a];
  let t2 = 1;

  for (let i = 1; i <= n; i++) {
    p1 = permutation(n, p1, t1);
    p2 = permutation(n, p2, t2);
    if (increase(p1) || increase(p2)) return i;
    t1 = 1 - t1;
    t2 = 1 - t2;
  }

  return -1;
};

const main = () => {
  const n = readInt();
  const a = readListInt();

  console.log(solve(n, a));
};

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 => string.trim());
  main();
});

const readLine = () => {
  return inputString[currentLine++];
};

const readInt = () => {
  return parseInt(inputString[currentLine++]);
};

const readListInt = () => {
  return inputString[currentLine++].split(" ").map(s => parseInt(s));
};

"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++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}
function getValue() {
  return parseInt(readline());
}
let mod = BigInt(1e9 + 7);
const solve = () => {
  let t = 1;
  while (t--) {
    let n = getValue();
    let arr = iInpArr();
    let arr1 = [...arr];
    const check = (arr) => {
      for (let i = 0; i < arr.length - 1; i++) {
        if (arr[i] > arr[i + 1]) return false;
      }
      return true;
    };
    const swap = (arr) => {
      for (let i = 0; i < arr.length; i += 2) {
        [arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];
      }
    };
    const rev = (arr) => {
      for (let i = 0; i < n; i++) {
        [arr[i], arr[n + i]] = [arr[n + i], arr[i]];
      }
    };
    if (n % 2 === 0) {
      if (check(arr)) {
        console.log(0);
        continue;
      }
      swap(arr);
      rev(arr1);
      if (check(arr) || check(arr1)) {
        console.log(1);
        continue;
      }
      rev(arr);
      swap(arr1);
      if (check(arr) || check(arr1)) {
        console.log(2);
        continue;
      }
      console.log(-1);
    } else {
      let ans = false;
      for (let i = 0; i <= n * 2; i++) {
        if (check(arr) || check(arr1)) {
          console.log(i);
          ans = true;
          break;
        }
        if (i % 2 === 0) {
          swap(arr);
          rev(arr1);
        } else {
          rev(arr);
          swap(arr1);
        }
      }
      if (ans === false) console.log(-1);
    }
  }
};
solve();

const readline = require("readline");
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
let input = [];
rl.on('line', line => {
    input.push(line);
})
rl.on('close', line => {
    var n = Number(input[0]);
    var arr = input[1].split(" ").map((i) => {
        return Number(i);
    })
    function op1(arr) {
        var temp = [];
        for (var i = 0; i < n; i++) {
            temp[2 * i + 1] = arr[2 * i];
            temp[2 * i] = arr[2 * i + 1];
        }
        return temp;
    }
    function op2(arr) {
        var temp = [];
        for (var i = 0; i < n; i++) {
            temp[i] = arr[i + n];
            temp[i + n] = arr[i];
        }
        return temp;
    }
    var sorted = arr.slice();
    sorted.sort((a, b) => {
        return a - b;
    })
    var set = new Set();
    var queue = [];
    queue.push(arr);
    set.add(arr.toString());
    var found = false;
    var step = 0;
    while (queue.length !== 0) {
        var l = queue.length;
        for (var m = 0; m < l; m++) {
            var curt = queue.shift();
            if (curt.toString() === sorted.toString()) {
                console.log(step);
                found = true;
                break;
            }
            var next1 = op1(curt);
            var next2 = op2(curt);
            if (!set.has(next1.toString())) {
                queue.push(next1);
                set.add(next1.toString());
            }
            if (!set.has(next2.toString())) {
                queue.push(next2);
                set.add(next2.toString());
            }
        }
        step++;
    }
    if (!found) {
        console.log(-1);
    }
})

const increase = a => {
  for (let i = 0; i < a.length; i++) {
    if (a[i] !== i + 1) return false;
  }
  return true;
};

const permutation = (n, a, tag) => {
  const b = [...a];
  if (tag === 0) {
    for (let j = 0; j < n; j++) {
      let w = b[2 * j];
      b[2 * j] = b[2 * j + 1];
      b[2 * j + 1] = w;
    }
  } else if (tag === 1) {
    for (let j = 0; j < n; j++) {
      let w = b[j];
      b[j] = b[n + j];
      b[n + j] = w;
    }
  }
  return b;
};

const solve = (n, a) => {
  if (increase(a)) return 0;

  let p1 = [...a];
  let t1 = 0;
  let p2 = [...a];
  let t2 = 1;
  for (let i = 1; i <= 4; i++) {
    p1 = permutation(n, p1, t1);
    p2 = permutation(n, p2, t2);
    if (increase(p1) || increase(p2)) return i;
    t1 = 1 - t1;
    t2 = 1 - t2;
  }

  return -1;
};

const main = () => {
  const n = readInt();
  const a = readListInt();

  console.log(solve(n, a));
};

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 => string.trim());
  main();
});

const readLine = () => {
  return inputString[currentLine++];
};

const readInt = () => {
  return parseInt(inputString[currentLine++]);
};

const readListInt = () => {
  return inputString[currentLine++].split(" ").map(s => parseInt(s));
};

const readline = require("readline");
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
let input = [];
rl.on('line', line => {
    input.push(line);
})
rl.on('close', line => {
    var n = Number(input[0]);
    var arr = input[1].split(" ").map((i) => {
        return Number(i);
    })
    function op1(arr) {
        var temp = [];
        for (var i = 0; i < n; i++) {
            temp[2 * i + 1] = arr[2 * i];
            temp[2 * i] = arr[2 * i + 1];
        }
        return temp;
    }
    function op2(arr) {
        var temp = [];
        for (var i = 0; i < n; i++) {
            temp[i] = arr[i + n];
            temp[i + n] = arr[i];
        }
        return temp;
    }
    var sorted = arr.slice();
    sorted.sort((a, b) => {
        return a - b;
    })
    var set = new Set();
    set.add(arr.toString());
    function helper(arr, set, step) {
        if (arr.toString() === sorted.toString()) {
            return step;
        }
        var min = Infinity;
        var next = op1(arr);
        if (!set.has(next.toString())) {
            set.add(next.toString());
            min = Math.min(helper(next, set, step + 1), min);
        }
        next = op2(arr);
        if (!set.has(next.toString())) {
            set.add(next.toString());
            min = Math.min(helper(next, set, step + 1), min);
        }
        return min;
    }
    var result = helper(arr, set, 0);
    if (result === Infinity) {
        console.log(-1);
    } else {
        console.log(result);
    }
})


function game(a,b){
  var p, x, q;
  p = Math.ceil((a+b)/2);
  q = a + b - p;
  var ans = new Set();
  for (var x=0; x<=p; x++){
    var y = a - (p-x);
    if(y<=q && y>=0) ans.add(x+y);
  }

  p = Math.floor((a+b)/2);
  q = a + b - p;

  for (var x=0; x<=p; x++){
    var y = a - (p-x);
    if(y<=q && y>=0) ans.add(x+y);
  }
  return Array.from(ans).sort(function(a, b) {
  return a - b;
});
}

var t = parseInt(readline());
var inp;

for (var i=0; i<t; i++){
    inp = readline().split(" ").map(x=>parseInt(x));
    var a = inp[0];
    var b = inp[1];
    var ans = game(a,b);
    print(ans.length);
    var s = "";
    for(item of ans){
        s += item + " ";
    }
    print(s);
}

"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++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
function iInpArr1() {
  return readline()
    .trim()
    .split("")
    .map((cur) => parseInt(cur));
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const sqrt = (n) => {
  let low = 1n,
    high = n,
    ans;
  while (low <= high) {
    let mid = (low + high) / 2n;
    if (mid * mid <= n) {
      ans = mid;
      low = mid + 1n;
    } else high = mid - 1n;
  }
  return ans;
};
const solve = () => {
  let t = getValue();
  while (t--) {
    let ans = [],
      obj = {};
    const push = (val) => {
      if (obj[val] === undefined) {
        ans.push(val);
        obj[val] = 1;
      }
    };
    let [a, b] = iInpArr();
    let right = Math.ceil((a + b) / 2);
    let left = Math.floor((a + b) / 2);
    let max = Math.max(a, b);
    let min = Math.min(a, b);
    let st = Math.abs(left - min);
    push(st);
    for (let i = 1; i <= min; i++) {
      push(st + i * 2);
    }
    let st1 = Math.abs(right - min);
    push(st1);
    for (let i = 1; i <= min; i++) {
      push(st1 + i * 2);
    }
    console.log(ans.length);
    console.log(ans.sort((a, b) => a - b).join(" "));
  }
};
solve();

var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

function main () {
	let T = rn();
	while (T--) {
		let [a, b] = rna();

		if (a > b)
			[a, b] = [b, a];

		let mb = Math.floor(Math.abs(a - b)/2);

		let times, inc;
		if ((a + b) % 2 == 0) {
			times = a + 1;
			inc = 2;
		} else {
			times = 2 * (a + 1);
			inc = 1;
		}

		const ans = [];
		for (let i = 0; i < times; i++) {
			ans.push(mb);
			mb += inc;
		}

		console.log(ans.length);
		console.log(ans.join(' '));
	}
}

"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++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
function iInpArr1() {
  return readline()
    .trim()
    .split("")
    .map((cur) => parseInt(cur));
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const sqrt = (n) => {
  let low = 1n,
    high = n,
    ans;
  while (low <= high) {
    let mid = (low + high) / 2n;
    if (mid * mid <= n) {
      ans = mid;
      low = mid + 1n;
    } else high = mid - 1n;
  }
  return ans;
};
const solve = () => {
  let t = getValue();
  while (t--) {
    let ans = [],
      obj = {};
    const push = (val) => {
      if (obj[val] === undefined) {
        ans.push(val);
        obj[val] = 1;
      }
    };
    let [a, b] = iInpArr();
    let right = Math.ceil((a + b) / 2);
    let left = Math.floor((a + b) / 2);
    let max = Math.max(a, b);
    let min = Math.min(a, b);
    let st = Math.abs(right - max);
    push(st);
    for (let i = 1; i <= min; i++) {
      push(i * 2);
    }
    let st1 = Math.abs(right - min);
    push(st1);
    for (let i = 1; i <= min; i++) {
      push(st1 + i * 2);
    }
    console.log(ans.length);
    console.log(ans.sort((a, b) => a - b).join(" "));
  }
};
solve();

function game(a,b){
  var p, x, q;
  p = Math.ceil((a+b)/2);
  q = a + b - p;
  var ans = new Set();
  for (var x=0; x<=p; x++){
    var y = a - (p-x);
    if(y<=q && y>=0) ans.add(x+y);
  }

  p = Math.floor((a+b)/2);
  q = a + b - p;

  for (var x=0; x<=p; x++){
    var y = a - (p-x);
    if(y<=q && y>=0) ans.add(x+y);
  }
  return Array.from(ans).sort();
}

var t = parseInt(readline());
var inp;

for (var i=0; i<t; i++){
    inp = readline().split(" ").map(x=>parseInt(x));
    var a = inp[0];
    var b = inp[1];
    var ans = game(a,b);
    print(ans.length);
    var s = "";
    for(item of ans){
        s += item + " ";
    }
    print(s);
}

function game(a,b){
  var p, x, q;
  p = Math.ceil((a+b)/2);
  q = a + b - p;
  var ans = new Set();
  for (var x=0; x<=p; x++){
    var y = a - (p-x);
    if(y<=q && y>=0) ans.add(x+y);
  }

  p = Math.floor((a+b)/2);
  q = a + b - p;

  for (var x=0; x<=p; x++){
    var y = a - (p-x);
    if(y<=q && y>=0) ans.add(x+y);
  }
  return ans;
}

var t = parseInt(readline());
var inp;

for (var i=0; i<t; i++){
    inp = readline().split(" ").map(x=>parseInt(x));
    var a = inp[0];
    var b = inp[1];
    var ans = game(a,b);
    print(ans.size);
    var s = "";
    for(item of ans){
        s += item + " ";
    }
    print(s);
}

function game(a,b){
  var p, x, q;
  p = Math.ceil((a+b)/2);
  q = a + b - p;
  var ans = new Set();
  for (var x=0; x<=p; x++){
    var y = a - (p-x);
    if(y<=q && y>=0) ans.add(x+y);
  }

  p = Math.floor((a+b)/2);
  q = a + b - p;

  for (var x=0; x<=p; x++){
    var y = a - (p-x);
    if(y<=q && y>=0) ans.add(x+y);
  }
  return ans;
}

var t = parseInt(readline());
var inp;

for (var i=0; i<t; i++){
    inp = readline().split(" ").map(x=>parseInt(x));
    var a = inp[0];
    var b = inp[1];
    var ans = game(a,b);
    for(item of ans){
        print(item);
    }
}


'use strict'

const {EOL} = require('os')

let ipt = ''
process.stdin.on('data', s => ipt += s)
process.stdin.on('end', () => {
  let s = ipt.split(EOL)[0]
  console.log(s
    .replace(/(\d)\s+(?=\d)/g, '$1*')
    .replace(/\s/g, '')
    .replace(/,/g, ', ')
    .replace(/\s?\.\.\./g, ' ...')
    .replace(/\*/g, ' ')
    .trim())
})

str = readline();
str = str.replace(/(\d+) +(\d+)/g, '$1_$2');
str = str.replace(/(\d+) +(\d+)/g, '$1_$2');
str = str.replace(/ /g, '');
str = str.replace(/_/g, ' ');
str = str.replace(/,/g, ', ');
str = str.replace(/\.\.\./g, ' ...');
str = str.replace(/  +/g, ' ');
str = str.replace(/ $/g, '');
str = str.replace(/^ /g, '');
write(str);

'use strict';

/*let input = `......,,,,,......  1234 1234  1234 , 1234 ...   ,   1234 ...   1234   ... ,   1234`.split('\n');
function print(output) {
	console.log(output);
}
function readline() {
	return input.shift();
}*/

//code

var inpStr = readline();
var inpArr = inpStr.trim().split('').reduce(function (acc, val, i, arr) {
	if (val !== " " || !(isNaN(parseInt(acc[acc.length - 1])) || isNaN(parseInt(arr[i + 1])))) {
		acc.push(val);
	}
	return acc;
}, []);

for (var i = 0; i < inpArr.length; i++) {
	if (inpArr[i] === ",") {
		inpArr.splice(i + 1, 0, " ");
		i++;
	} else if (inpArr[i] === "." && inpArr[i + 1] === "." && inpArr[i + 2] === ".") {
		if (inpArr[i - 1] !== " ") {
			inpArr.splice(i, 0, " ");
			i += 3;
		} else {
			i += 2;
		}
	}
}

print(inpArr.join('').trim());

'use strict';

/*let input = `1  2     3 6 4 545 45 12`.split('\n');
function print(output) {
	console.log(output);
}
function readline() {
	return input.shift();
}*/

//code

var inpStr = readline();
var inpArr = inpStr.trim().split('').reduce(function (acc, val, i, arr) {
	if (val !== " " || !(isNaN(parseInt(acc[acc.length - 1])) || isNaN(parseInt(arr[i + 1])))) {
		acc.push(val);
	}
	return acc;
}, []);

for (var i = 0; i < inpArr.length; i++) {
	if (inpArr[i] === ",") {
		inpArr.splice(i + 1, 0, " ");
	} else if (inpArr[i] === "." && inpArr[i + 1] === "." && inpArr[i + 2] === "." && inpArr[i - 1] !== " ") {
		inpArr.splice(i, 0, " ");
		i += 3;
	}
}

print(inpArr.join('').trim());

'use strict';

/*let input = `...,1,2,3,...`.split('\n');
function print(output) {
	console.log(output);
}
function readline() {
	return input.shift();
}*/

//code

var inpStr = readline();
var inpArr = inpStr.split('').filter(function (el) {
	return el != " ";
});
for (var i = 0; i < inpArr.length; i++) {
	if (inpArr[i] === ",") {
		inpArr.splice(i + 1, 0, " ");
	} else if (inpArr[i] === "." && inpArr[i + 1] === "." && inpArr[i + 2] === "." && inpArr[i - 1] !== " ") {
		inpArr.splice(i, 0, " ");
		i += 3;
	}
}
print(inpArr.join('').trim());

str = readline();
str = str.replace(/ /g, '');
str = str.replace(/,/g, ', ');
str = str.replace(/\.\.\./g, ' ...');
str = str.replace(/  +/g, ' ');
str = str.replace(/ $/g, '');
str = str.replace(/^ /g, '');
write(str);

str = readline();
str = str.replace(/,/g, ', ');
str = str.replace(/(\d+?) +?,/g, '$1,');
str = str.replace(/\.\.\./g, ' ...');
str = str.replace(/  +/g, ' ');
str = str.replace(/ $/g, '');
str = str.replace(/^ /g, '');
write(str);

str = readline();
str = str.replace(/(\d+?) +?(\d+?)/g, '$1')
str = str.replace(/,/g, ', ');
str = str.replace(/(\d+?) +/g, '$1');
str = str.replace(/\.\.\./g, ' ...');
str = str.replace(/  +/g, ' ');
str = str.replace(/ $/g, '');
str = str.replace(/^ /g, '');
write(str);

'use strict'

const {EOL} = require('os')

let ipt = ''
process.stdin.on('data', s => ipt += s)
process.stdin.on('end', () => {
  let s = ipt.split(EOL)[0]
  console.log(s
    .replace(/(\d)\s+(\d)/, '$1*$2')
    .replace(/\s/g, '')
    .replace(/,/g, ', ')
    .replace(/\s?\.\.\./g, ' ...')
    .replace(/\*/g, ' ')
    .trim())
})


'use strict';
// HEADER:
const print = console.log;
let IS_MULTITEST, testN;
const pcalc = testN=>{
  let res = calc(testN);
  if (Array.isArray(res)){
    pa(res);
  } else if (Number.isFinite(res) || typeof res=='string'){
    print(res);
  }
};

const main = ()=>{
  if (IS_MULTITEST){
    let T = +readline()
    for (testN=1; testN<=T; testN++)
      pcalc(T);
  } else
   pcalc();
};

const lines = [];
const rl = require('readline').createInterface({
   input: process.stdin, output: process.stdout});
rl.on('line', line=>{
  lines.push(line);
});
rl.on('close', main);
let rli = 0;
const readline = ()=>lines[rli++];
const L = process.env.DEBUG ? console.log : ()=>{};
const LT = obj=>L(`Test #${testN}`, obj);

const ra = ()=>readline().split(' ').map(a=>+a)
const pa = arr=>print(arr.join(' '));

// SOLUTION:
IS_MULTITEST = 1;

const calc = ()=>{
  // READING:
  let [n] = ra();
  let A = ra();
  LT({n, A});

  // PROCESSING:
  let min = n-1;
  for (let i=0; i<n; i++){
    for (let j=i+1; j<n; j++){
      let step = (A[j]-A[i])/(j-i);
      let cnt = 0;
      for (let k=0; k<n; k++){
        if (Math.abs(A[i]-step*(i-k) - A[k])>0.000001)
          cnt++;
      }
      min = Math.min(cnt, min)
    }
  }
  return min;
};

let _inputLines;
let _lineNumber = 0;
let inputReader = _inputReader();

function _main() {
  _inputLines = _inputData
    .trim()
    .split("\n")
    .map((string) => {
      return string.trim();
    });

  let t = inputReader.readNumber();

  function solve() {
    let n = inputReader.readNumber();
    let a = inputReader.readNumberArray();
    let ans = Infinity;
    for (let i = 0; i < n; i++) {
      for (let j = i + 1; j < n; j++) {
        let cur = 0;
        for (let k = 0; k < n; k++) {
          if ((a[j] - a[i]) * (k - i) != (a[k] - a[i]) * (j - i)) cur++;
        }
        ans = Math.min(ans, cur);
      }
    }
    console.log(ans == Infinity ? 0 : ans);
  }

  while (t--) {
    solve();
  }
}

var _inputData = "";
function cacheInput(data) {
  _inputData += data;
}

process.stdin.resume();
process.stdin.setEncoding("utf8");
process.stdin.on("data", cacheInput).on("end", _main);

function _inputReader() {
  function readNumber() {
    return Number(_inputLines[_lineNumber++]);
  }

  function readNumberArray() {
    return _inputLines[_lineNumber++].split(" ").map((val) => Number(val));
  }

  return {
    readNumber,
    readNumberArray,
  };
}

var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

function isEqual (a, b) {
	const prec = 1e-3;
	return Math.abs(a - b) < prec;
}

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const a = rna();

		let mxm = 1;
		for (let i = 0; i < n; i++) {
			for (let j = i + 1; j < n; j++) {
				const d = (a[j] - a[i]) / (j-i);
				const A = a[j] - a[i];
				const B = j - i;
				let matches = 0;
				for (let k = 0; k < n; k++) {
					matches += B*a[k] ==  B*a[i] + A*(k-i);
				}
				mxm = Math.max(mxm, matches);
			}
		}

		console.log(n-mxm);
	}
}

var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

const INF = 1000;

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const a = rna();

		let mxm = 1;
		for (let i = 0; i < n; i++) {
			for (let j = i + 1; j < n; j++) {
				const d = (a[j] - a[i]) / (j-i);
				let matches = 0;
				for (let k = 0; i+k < n; k++) {
					matches += Math.abs(a[i+k] - (a[i] + d*k)) < 1e-3;
				}
				mxm = Math.max(mxm, matches);
			}
		}

		console.log(n-mxm);
	}
}

var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

const INF = 1000;

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const a = rna();

		let mxm = 1;
		for (let i = 0; i < n; i++) {
			for (let j = i + 1; j < n; j++) {
				const d = (a[j] - a[i])/ (j-i);
				let matches = 0;
				for (let k = 0; i+k < n; k++) {
					matches += a[i+k] == a[i] + d*k;
				}
				mxm = Math.max(mxm, matches);
			}
		}

		console.log(n-mxm);
	}
}


var s0=readline().split(' ')
var n=+s0[0],have=+s0[1];
var s=readline();
var l=-1,h=n-2;
while(l+1<h) {
    var m=l+Math.floor((h-l)/2);
    var at=0; var ok=true; var need=1;
    while(ok&&at<n-1) {
        var to=at+m+1;
        if(to>n-1) to=n-1;
        while(to>at&&s[to]=='1') --to;
        if(to==at) { ok=false; break; }
        ++need; at=to;
    }
    //print(m," -> ",need," (",ok,")");
    if(ok&&need<=have) h=m; else l=m;
}
print(h);

var n, k
s1 = readline().split(' ')
n = 1*s1[0]
k = 1*s1[1]
s = readline()

var l = 0
var r = n
var Fail = 0
for (var i = 0; i < n; ++i) {
    if (s[i] == '1') {
        Fail = 1
    }
}
if (Fail == 0 && k == n) {
    print(0)
} else {
while (l + 1 < r) {
    var m = Math.floor((l + r) / 2)

    var rem = k
    var last = 0
    var prev = -1
    var fail = 0
    for (var i = 0; i < n; ++i) {
        if (s[i] == '0') {
            prev = i
        }
        if (i == 0 || i == last + m || i == n-1) {
            if (prev == -1) {
                fail = 1
                break
            }

            last = prev
            --rem
            prev = -1
        }
    }

    if (fail == 1 || rem < 0) {
        l = m
    } else {
        r = m
    }
}
print(r-1)
}


const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

rl.on('line', (str) => {
  const ans = str + [...str].reverse().join('');
  console.log(ans);
});

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
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';}}
	};
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//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 s = next();
	var output = s;
	for(var i = 0; i < s.length; i++){
		output += s[s.length - 1 - i];
	}
	myout(output);
}

var a = readline()
write(a)
write(a.split("").reverse().join(""))


const numSplit = (n) => n.toString().split("");

var num = numSplit(readline());

const sumDigits = (numArr) => numSplit(numArr.reduce((sum,n) => sum + Number(n),0));

var count = 0;

const recursive = (numArr) => {
    if (numArr.length == 1) return;
    count++;
    recursive(sumDigits(numArr));
}

recursive(num);

print(count);

/* TEST CASE
input
0
output
0
input
10
output
1
input
991
output
3
 */
function sumOfDigits(s) {
    var ret = 0;
    for (var i = s.length - 1; i >= 0; i--) {
    	ret += parseInt(s[i]);
    }

    return ret.toString();
}

function main() {
	var s = readline();
	var answer = 0;
	while (s.length > 1) {
		s = sumOfDigits(s);
		answer++;
	}
	print(answer);
}

main();

const readline = require('readline');
let inputs = [];
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
rl.on('line', lineInput => {
    inputs.push(lineInput)
})

rl.on('close', () => {
	const n = inputs[0].split('').map((a) => {return parseInt(a)});
    console.log(solution(n));

})

// let stdin = process.stdin;
// stdin.setEncoding('utf8');

// stdin.on('data', function (data) {
//     let input = data.split('\n');
//     let n = input[0].split('').map((a) => {return parseInt(a)});

//     console.log(solution(n));
// });

function solution(n) {
	if (n.length === 1) {
		return 0;
	}
	let sumDig = n.reduce((a, b) => {return a+b}, 0);
	let count = 1;
	while (parseInt(sumDig / 10) !== 0) {
		count += 1;
		sumDig = findSum(sumDig)
	}
	return count;
}

function findSum(n) {
	let sum = 0;
	let dig = 0;
	while (n !== 0) {
		dig = n % 10;
		sum += dig;
		n = parseInt(n / 10);
	}
	return sum;
}

line = readline();
var count =0;
while(line.length > 1) {
    count++;
    var result = 0;
    for(var i =0; i <line.length; i++) {
        result +=Number(line[i]);
    }
    line = String(result);
}
print(count);

var toInt = x => parseInt(x);
var toSum = (a, b) =>(a+b);
var isum = x => x.split('').map(toInt).reduce(toSum);

var x = readline();

var q = [x], res=0;
while(q.length > 0) {
    var x = q.shift();

    if (x.length>=2) {
        q.push(isum(x)+'');
        res++;
    }
}
print(res);

const numSplit = (n) => n.toString().split("");

var num = readline();
/*
const sumDigits = (numArr) => numSplit(numArr.reduce((sum,n) => sum + n,0));

let count = 0;

const recursive = (numArr) => {
    if (numArr.length == 1) return;
    count++;
    recursive(sumDigits(numArr));
}

recursive(num);
*/
print(num);

const numSplit = (n) => n.toString().split("");

var num = numSplit(readline());
/*
const sumDigits = (numArr) => numSplit(numArr.reduce((sum,n) => sum + Number(n),0));

let count = 0;

const recursive = (numArr) => {
    if (numArr.length == 1) return;
    count++;
    recursive(sumDigits(numArr));
}

recursive(num);
*/
print(num);

const numSplit = (n) => n.toString().split("");

var num = numSplit(readline());
/*
const sumDigits = (numArr) => numSplit(numArr.reduce((sum,n) => sum + n,0));

let count = 0;

const recursive = (numArr) => {
    if (numArr.length == 1) return;
    count++;
    recursive(sumDigits(numArr));
}

recursive(num);
*/
print(num);

/*const numSplit = (n) => n.toString().split("");

const num = numSplit(readLine());

const sumDigits = (numArr) => numSplit(numArr.reduce((sum,n) => sum + n,0));

let count = 0;

const recursive = (numArr) => {
    if (numArr.length == 1) return;
    count++;
    recursive(sumDigits(numArr));
}

recursive(num);
*/
print(0);

const numSplit = (n) => n.toString().split("");

var num = readline();
/*
const sumDigits = (numArr) => numSplit(numArr.reduce((sum,n) => sum + n,0));

let count = 0;

const recursive = (numArr) => {
    if (numArr.length == 1) return;
    count++;
    recursive(sumDigits(numArr));
}

recursive(num);
*/
print(numSplit(num));

var toInt = x => parseInt(x);
var toSum = (a, b) =>(a+b);
var isum = x => (x+'').split('').map(toInt).reduce(toSum);

var x = parseInt(readline());
var q = [x], res=0;
while(q.length > 0) {
    var x = q.shift();
    if (x>=10) {
        q.push(isum(x));
        res++;
    }
}
print(res);

var toInt = x => parseInt(x);
var toSum = (a, b) =>(a+b);
var isum = x => x.split('').map(toInt).reduce(toSum);

var x = readline();

var q = [x], res=0;
while(q.length > 0) {
    var x = q.shift();

    if (x.length>2) {
        q.push(isum(x)+'');
        res++;
    }
}
print(res);


function get(mp, line) {
    if (!mp.has(line)) {
        var obj = new Object();
        var ll = line.split(/ /);
        obj.name = ll[0];
        obj.vers = parseInt(ll[1]);
        obj.used = false;
        obj.links = [];
        mp.set(line, obj);
    }
    return mp.get(line);
}

function main(rl) {
    var n = parseInt(rl());
    var mp = new Map();
    var head = null;
    for (var i = 0; i < n; ++i) {
        var obj0 = get(mp, rl());
        if (head == null)
            head = obj0;

        var num_links = parseInt(rl());
        for (var j = 0; j < num_links; ++j) {
            obj0.links.push(get(mp, rl()));
        }
        rl();
    }

    var res = [];

    mp.clear();
    var queue0 = [];
    var queue1 = [head];
    while (0 < queue0.length || 0 < queue1.length) {
        queue0 = queue1; queue1 = [];
        queue0.sort((a, b) => (b.vers - a.vers));

        queue0.forEach(function(it) {
            if (mp.has(it.name)) return;
            mp.set(it.name, true);

            res.push(it);
            it.links.forEach(function(it0) {
                if (it0.used) return;
                it0.used = true;
                if (mp.has(it0.name)) return;
                queue1.push(it0);
            });
        });
    }

    res.shift();
    res.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name));
    write(res.length + '\n');
    res.forEach(function(it0) {
        write(it0.name + " " + it0.vers + "\n");
    });

}

main(readline);

function getInput () {
    var prCount = parseInt(readline(), 10);

    var input = [];

    for (var i = 1; i <= prCount; i++) {
        var pr = {};

        pr.name = readline();
        pr.deps = [];

        var depsCount = parseInt(readline(), 10);
        for (var k = 1; k <= depsCount; k++) {
            pr.deps.push(readline());
        }

        input.push(pr);

        readline();
    }

    return input;
}

function getDeps (input) {
    var allProjects = {}, key = 0, allKeys = [];
    var graph = [];

    input.forEach(function (project) {
        if (allProjects[project.name] == undefined) {
            allProjects[project.name] = {key: key, ver: +project.name.split(' ')[1], name: project.name.split(' ')[0]};
            allKeys.push(project.name)
            key++;
        }

        project.deps.forEach(function (prName) {
            if (allProjects[prName] == undefined) {
                allProjects[prName] = key;
                allProjects[prName] = {key: key, ver: +prName.split(' ')[1], name: prName.split(' ')[0]};
                allKeys.push(prName)
                key++;
            }
        })

    })

    input.forEach(function(project){
        var prIndex = allProjects[project.name].key;
        graph[prIndex] = [];

        project.deps.forEach(function (prName) {
            graph[prIndex][allProjects[prName].key] = 1
        });
    });

    initialProject = [input[0].name];
    function findInList(pr, prList) {
        var prName = allProjects[pr].name
        var prIndex = -1;
        prList.forEach(function(proj, index) {
            if (allProjects[proj].name == prName) {
                prIndex = index
            }
        })
        return prIndex;
    };

    function getDepsRoutine (prList) {
        var subresult = [];

        prList.forEach(function(prName){
            graph[allProjects[prName].key].forEach(function(el, index){
                var depName = allKeys[index];
                if (el == 1 && findInList(depName, result) == -1) {
                    var prIndexInSubresult = findInList(depName, subresult);
                    if (prIndexInSubresult !== -1) {
                        if (allProjects[subresult[prIndexInSubresult]].ver < allProjects[depName].ver)
                            subresult[prIndexInSubresult] = depName;
                    } else {
                        subresult.push(depName)
                    }
                }
            });
        });

        result = result.concat(subresult);
        if (subresult.length > 0)
            getDepsRoutine(subresult);
    }

    var result = [initialProject[0]];

    getDepsRoutine(initialProject)
    result.shift();

    return result.sort();
}

var answer = getDeps(getInput());

print(answer.length);

answer.forEach(function(el){
    print(el)
})

function getInput () {
    var prCount = parseInt(readline(), 10);

    var input = [];

    for (var i = 1; i <= prCount; i++) {
        var pr = {};

        pr.name = readline();
        pr.deps = [];

        var depsCount = parseInt(readline(), 10);
        for (var k = 1; k <= depsCount; k++) {
            pr.deps.push(readline());
        }

        input.push(pr);

        readline();
    }

    return input;
}

function getDeps (input) {
    var allProjects = {}, key = 0, allKeys = [];
    var graph = [];

    input.forEach(function (project) {
        if (allProjects[project.name] == undefined) {
            allProjects[project.name] = key;
            allKeys.push(project.name)
            key++;
        }

        project.deps.forEach(function (prName) {
            if (allProjects[prName] == undefined) {
                allProjects[prName] = key;
                allKeys.push(prName)
                key++;
            }
        })

    })

    input.forEach(function(project){
        var prIndex = allProjects[project.name];
        graph[prIndex] = [];

        project.deps.forEach(function (prName) {
            graph[prIndex][allProjects[prName]] = 1
        });
    });

    initialProject = [input[0].name];
    function findInList(pr, prList) {
        var prName = pr.split(' ')[0]
        var prIndex = -1;
        prList.forEach(function(proj, index) {
            if (proj.split(' ')[0] == prName) {
                prIndex = index
            }
        })
        return prIndex;
    };

    function getDepsRoutine (prList) {
        var subresult = [];

        prList.forEach(function(prName){
            graph[allProjects[prName]].forEach(function(el, index){
                var depName = allKeys[index];
                if (el == 1 && findInList(depName, result) == -1) {
                    var prIndexInSubresult = findInList(depName, subresult);
                    if (prIndexInSubresult !== -1) {
                        if (subresult[prIndexInSubresult].split(' ')[1] < depName.split(' ')[1])
                            subresult.splice(prIndexInSubresult, 1, depName);
                    } else {
                        subresult.push(depName)
                    }
                }
            });
        });

        result = result.concat(subresult);
        if (subresult.length > 0)
            getDepsRoutine(subresult);
    }

    var result = [initialProject[0]];

    getDepsRoutine(initialProject)
    result.shift();

    return result.sort();
}

var answer = getDeps(getInput());

print(answer.length);

answer.forEach(function(el){
    print(el)
})

function getInput () {
    var prCount = parseInt(readline(), 10);

    var input = [];

    for (var i = 1; i <= prCount; i++) {
        var pr = {};

        pr.name = readline();
        pr.deps = [];

        var depsCount = parseInt(readline(), 10);
        for (var k = 1; k <= depsCount; k++) {
            pr.deps.push(readline());
        }

        input.push(pr);

        readline();
    }

    return input;
}

function getDeps (input) {
    var allProjects = {}, key = 0, allKeys = [];
    var graph = [];

    input.forEach(function (project) {
        if (allProjects[project.name] == undefined) {
            allProjects[project.name] = {key: key, ver: project.name.split(' ')[0], name: project.name.split(' ')[1]};
            allKeys.push(project.name)
            key++;
        }

        project.deps.forEach(function (prName) {
            if (allProjects[prName] == undefined) {
                allProjects[prName] = key;
                allProjects[prName] = {key: key, ver: +prName.split(' ')[0], name: prName.split(' ')[1]};
                allKeys.push(prName)
                key++;
            }
        })

    })

    input.forEach(function(project){
        var prIndex = allProjects[project.name].key;
        graph[prIndex] = [];

        project.deps.forEach(function (prName) {
            graph[prIndex][allProjects[prName].key] = 1
        });
    });

    initialProject = [input[0].name];
    function findInList(pr, prList) {
        var prName = allProjects[pr].name
        var prIndex = -1;
        prList.forEach(function(proj, index) {
            if (allProjects[proj].name == prName) {
                prIndex = index
            }
        })
        return prIndex;
    };

    function getDepsRoutine (prList) {
        var subresult = [];

        prList.forEach(function(prName){
            graph[allProjects[prName].key].forEach(function(el, index){
                var depName = allKeys[index];
                if (el == 1 && findInList(depName, result) == -1) {
                    var prIndexInSubresult = findInList(depName, subresult);
                    if (prIndexInSubresult !== -1) {
                        if (allProjects[subresult[prIndexInSubresult]].ver < allProjects[depName].ver)
                            subresult[prIndexInSubresult] = depName;
                    } else {
                        subresult.push(depName)
                    }
                }
            });
        });

        result = result.concat(subresult);
        if (subresult.length > 0)
            getDepsRoutine(subresult);
    }

    var result = [initialProject[0]];

    getDepsRoutine(initialProject)
    result.shift();

    return result.sort();
}

var answer = getDeps(getInput());

print(answer.length);

answer.forEach(function(el){
    print(el)
})


"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++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
function iInpArr1() {
  return readline()
    .trim()
    .split("")
    .map((cur) => parseInt(cur));
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const sqrt = (n) => {
  let low = 1n,
    high = n,
    ans;
  while (low <= high) {
    let mid = (low + high) / 2n;
    if (mid * mid <= n) {
      ans = mid;
      low = mid + 1n;
    } else high = mid - 1n;
  }
  return ans;
};

const solve = () => {
  let t = getValue();
  while (t--) {
    let [n, k] = iInpArr();
    let arr = iInpArr();
    let pos = [],
      neg = [];
    for (let i = 0; i < n; i++) {
      if (arr[i] < 0) neg.push(Math.abs(arr[i]));
      else pos.push(arr[i]);
    }
    let sum = 0,
      max1 = -Infinity,
      max2 = -Infinity;
    if (neg.length !== 0) {
      neg.sort((a, b) => b - a);
      max1 = neg[0];
      let j = 0;
      while (j < neg.length) {
        sum += neg[j] * 2;
        j += k;
      }
    }
    if (pos.length !== 0) {
      pos.sort((a, b) => b - a);
      max2 = pos[0];
      let j = 0;
      while (j < pos.length) {
        sum += pos[j] * 2;
        j += k;
      }
    }
    if (max1 > max2) sum -= neg[0];
    else sum -= pos[0];
    console.log(sum);
  }
};
solve();

'use strict';

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();
    });

    main();
});

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

function print(...args) {
    console.log(...args);
}

function main() {
    const testCases = readline();

    for (let i = 0 ; i < testCases ; i++) {
        const [maxCases, limit] = readline().split(" ");
        const bagLimit = Number(limit);
        const depotPositions = readline().split(" ").slice(0, maxCases).map(n => Number(n));

        const negativePositions = depotPositions.filter(n => n < 0).map(n => n * -1).sort((a, b) => a - b);
        const positivePositions = depotPositions.filter(n => n >= 0).sort((a, b) => a - b);

        function deliverBags(sortedPositions, bagCarryingLimit, shouldReturn) {
            let totalDistance = 0;

            if (!shouldReturn) {
                totalDistance -= sortedPositions[sortedPositions.length - 1];
            }

            // Pick next
            for (let positionIndex = sortedPositions.length - 1 ; positionIndex >= 0 ; positionIndex -= bagCarryingLimit) {
                totalDistance += sortedPositions[positionIndex] * 2;
            }
            return totalDistance;
        }

        if (positivePositions.length > 0 && negativePositions.length > 0) {
            let totalDeliveryDistance = 0;
            if (positivePositions[positivePositions.length - 1] >= negativePositions[negativePositions.length - 1]) {
                totalDeliveryDistance += deliverBags(negativePositions, bagLimit, true);
                totalDeliveryDistance += deliverBags(positivePositions, bagLimit, false);
                print(totalDeliveryDistance);
            } else {
                totalDeliveryDistance += deliverBags(positivePositions, bagLimit, true);
                totalDeliveryDistance += deliverBags(negativePositions, bagLimit, false);
                print(totalDeliveryDistance);
            }
        } else if (positivePositions.length > 0) {
            print(deliverBags(positivePositions, bagLimit, false));
        } else {
            print(deliverBags(negativePositions, bagLimit, false));
        }
    }
}

const main = () => {

	const calc = (arr, k) => {
		// print(arr);
		// print(arr.length);
		if (arr.length === 0)
			return 0;
		arr.sort(function(a, b){return a-b});
		var ans2 = 0;
		var i = arr.length - 1; // take the last item firstChild
		while (i >= 0) {
			ans2 += 2 * arr[i];
			j = Math.max(0, i - k + 1);
			i = j - 1;
		}
		ans2 -= arr[arr.length - 1]; // don't come back
		return ans2;
	}

	var t = readInt();
	const allans = [];
	while (t--) {
		var nk = readIntArr();
		var n = nk[0], k = nk[1];
		var a = readIntArr();
		// print(a);
		var pos = []; var neg = [];
		for (var x of a) {
			if (x > 0)
				pos.push(x);
			else
				neg.push(-x);
		}
		var pos2 = calc(pos, k);
		var neg2 = calc(neg, k);
		var extra = 0;
		if (pos.length > 0 && neg.length > 0) { // 1 of them needs to come back
			extra = Math.min(pos[pos.length - 1], neg[neg.length - 1]);
		}
		// print("pos2:" + pos2 + " neg2:" + neg2 + " extra:" + extra);
		var ans = pos2 + neg2 + extra;
		allans.push(ans);
	}
	multiLineArrayPrint(allans);

	return;
}

const readInt = () => parseInt(readline());
const readString = () => readline();
const readIntArr = () => readline().split(" ").map(zzzz => parseInt(zzzz));
const parseLong = (string) => { // javascript's largest long is < (1<<62)
	var n = string.length;
	var res = 0;
	for (var i = 0; i < n; i++) {
		res *= 10;
		res += parseInt(string[i]);
	}
	return res;
}
const readLong = () => parseLong(readLong());
const readLongArr = () => readline().split(" ").map(zzzz => parseLong(zzzz));
const oneLineArrayPrint = (arr) => print(arr.map(zzzz => zzzz.toString()).join(' '));
const multiLineArrayPrint = (arr) => print(arr.map(zzzz => zzzz.toString()).join('\n'));
const multiLineArrayOfArraysPrint = (arr) => print(arr.map(yyyy => yyyy.map(zzzz => zzzz.toString()).join(' ')).join('\n'));
const makeArr = (defaultVal, dimensionsArr) => {
	var n = dimensionsArr.length;
	if (n === 1) return Array(dimensionsArr[0]).fill(defaultVal);
	else {
		var temp = [];
		for (var i = 0; i < dimensionsArr[0]; i++)
			temp.push(makeArr(defaultVal, dimensionsArr.slice(1)));
		return temp;
	}
}

for (_ = 0; _ < 1; _++) {
	main();
}

// newline for testing
 //newline for testing
// codeforces js cannot use "let" keyword. use "var" instead
// codeforces js cannot destructure arrays

process.stdin.setEncoding('utf-8')
const readline = require('readline')

const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    }
)

let count = -1
let inputArr = []

rl.on('line', data => {
    if (count === -1) {
        count = +data * 2
    } else if (count !== 0) {
        inputArr.push(data.trim())
        count--
    }
    // max number 2^(53) - 1 ~~ 10^(15)
    if (count === 0) {
        inputArr = inputArr.map(i => i.split(' ').map(j => +j))
        main()
        process.exit(0)
    }
})

function solve([n, k], arr) {
    const min = arr.filter(i => i < 0).sort((a, b) => a - b),
        max = (arr.filter(i => i >= 0).sort((a, b) => b - a))

    let lastM = 0, lastP = 0
    let aa = min.length, bb = max.length
    if (min.length !== 0) {
        lastM = Math.abs(min[0])
    }
    if (max.length !== 0) {
        lastP = max[0]
    }
    let tmp = k, ds = 0
    while (aa !== 0) {
        aa--
        if (!--tmp) {
            break
        }
    }
    tmp = k
    while (bb !== 0) {
        bb--
        if (!--tmp) {
            break
        }
    }
    while (aa !== 0) {
        tmp = k
        ds += Math.abs(min[min.length - aa]) * 2
        while (aa !== 0) {
            aa--
            if (!--tmp) {
                break
            }
        }
    }
    while (bb !== 0) {
        tmp = k
        ds += max[max.length - bb] * 2
        while (bb !== 0) {
            bb--
            if (!--tmp) {
                break
            }
        }
    }
    if (lastM === 0) {
        console.log(lastP + ds)
    } else if (lastP === 0) {
        console.log(lastM + ds)
    } else {
        console.log(Math.min(ds + lastM * 2 + lastP, ds + lastP * 2 + lastM))
    }
}

function main() {
    for (let i = 0; i < inputArr.length; i += 2) solve(inputArr[i], inputArr[i + 1])
}

var stdin_input = "";
var stdin_input_itr;
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { stdin_input_itr = stdin_input.split('\n').values(); main(); });

const rl = () => stdin_input_itr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

var deb; const log = msg => (typeof deb != "undefined") && console.log("DEBUG", msg);

function main () {
	let T = rn();
	while (T--) {
		const [n, k] = rna();
		const x = rna();
		const a = [], b = [];
		let mxd = 0;
		for (let i = 0; i < n; i++) {
			if (x[i] > 0) a.push(x[i]);
			if (x[i] < 0) b.push(-x[i]);
			mxd = Math.max(mxd, Math.abs(x[i]));
		}

		function solve (x) {
			x.sort((first, second) => first - second);

			let dist = 0;
			const start = (x.length - 1 + k) % k;
			for (let i = start; i < x.length; i += k) {
				dist += 2 * x[i];
			}
			return dist;
		}

		const ans = solve(a) + solve(b) - mxd;
		console.log(ans);
	}
}

var stdin_input = "";
var stdin_input_itr;
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { stdin_input_itr = stdin_input.split('\n').values(); main(); });

const rl = () => stdin_input_itr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

var deb; const log = msg => (typeof deb != "undefined") && console.log("DEBUG", msg);

function main () {
	let T = rn();
	while (T--) {
		const [n, k] = rna();
		const x = rna();
		const a = [], b = [];
		let mxd = 0;
		for (let i = 0; i < n; i++) {
			if (x[i] > 0) a.push(x[i]);
			if (x[i] < 0) b.push(-x[i]);
			mxd = Math.max(mxd, Math.abs(x[i]));
		}

		function solve (x) {
			x.sort((first, second) => second - first);
			let avl = 0, dist = 0;
			for (let i = 0; i < x.length; i++) {
				if (avl == 0) dist += 2*x[i], avl = k;
				avl--;
			}
			return dist;
		}

		const ans = solve(a) + solve(b) - mxd;
		console.log(ans);
	}
}

var n=parseInt(readline());
for(var i=0;i<n;i++){
  var k=readline().split(" ")[1];
  var depots=readline().split(" ");
  depots.sort((a,b)=>a-b);
  var positive_depots=[];
  var positive_groups=[];
  var negative_depots=[];
  var negative_groups=[];
  var pempty=false;
  var nempty=false;
  var last_group;
  var distance=0;
  for(var depot of depots){
    depot>0?positive_depots.push(depot):negative_depots.push(depot);
  }
  positive_depots=positive_depots.reverse();
  for(var i2=0;i2<negative_depots.length;i2++){
    if(i2%k===0)negative_groups.push([]);
    negative_groups[Math.floor(i2/k)].push(negative_depots[i2]*-1);
  }
  for(var i3=0;i3<positive_depots.length;i3++){
    if(i3%k===0)positive_groups.push([]);
    positive_groups[Math.floor(i3/k)].push(positive_depots[i3]);
  }
  if(!positive_groups.length)positive_groups=[[0]];
  if(!negative_groups.length)negative_groups=[[0]];
  2*positive_groups[0][0]>2*negative_groups[0][0]?last_group="+":last_group="-";
  for(var i4=0;i4<positive_groups.length;i4++){
    distance+=2*positive_groups[i4][0];
  }
  for(var i5=0;i5<negative_groups.length;i5++){
    distance+=2*negative_groups[i5][0];
  }
  last_group=="+"?distance-=positive_groups[0][0]:distance-=negative_groups[0][0];
  print(distance);
}

'use strict';

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();
    });

    main();
});

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

function print(...args) {
    console.log(...args);
}

function main() {
    const testCases = readline();

    for (let i = 0 ; i < testCases ; i++) {
        const [maxCases, limit] = readline().split(" ");
        const bagLimit = Number(limit);
        const depotPositions = readline().split(" ").slice(0, maxCases).map(n => Number(n));

        const negativePositions = depotPositions.filter(n => n < 0).map(n => n * -1).sort((a, b) => a - b);
        const positivePositions = depotPositions.filter(n => n > 0).sort((a, b) => a - b);

        function deliverBags(sortedPositions, bagCarryingLimit, shouldReturn) {
            let totalDistance = 0;

            if (!shouldReturn) {
                totalDistance -= sortedPositions[sortedPositions.length - 1];
            }

            // Pick next
            for (let positionIndex = sortedPositions.length - 1 ; positionIndex >= 0 ; positionIndex -= bagCarryingLimit) {
                totalDistance += sortedPositions[positionIndex] * 2;
            }
            return totalDistance;
        }

        if (positivePositions.length > 0 && negativePositions.length > 0) {
            let totalDeliveryDistance = 0;
            if (positivePositions[positivePositions.length - 1] >= negativePositions[negativePositions.length - 1]) {
                totalDeliveryDistance += deliverBags(negativePositions, bagLimit, true);
                totalDeliveryDistance += deliverBags(positivePositions, bagLimit, false);
                print(totalDeliveryDistance);
            } else {
                totalDeliveryDistance += deliverBags(positivePositions, bagLimit, true);
                totalDeliveryDistance += deliverBags(negativePositions, bagLimit, false);
                print(totalDeliveryDistance);
            }
        } else if (positivePositions.length > 0) {
            print(deliverBags(positivePositions, bagLimit, false));
        } else {
            print(deliverBags(negativePositions, bagLimit, false));
        }
    }
}

'use strict';

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();
    });

    main();
});

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

function print(...args) {
    console.log(...args);
}

function main() {
    const testCases = readline();

    for (let i = 0 ; i < testCases ; i++) {
        const [maxCases, limit] = readline().split(" ");
        const bagLimit = parseInt(limit);
        const depotPositions = readline().split(" ").slice(0, maxCases).map(n => parseInt(n));

        const negativePositions = depotPositions.filter(n => n < 0).map(n => n * -1).sort((a, b) => a - b);
        const positivePositions = depotPositions.filter(n => n > 0).sort((a, b) => a - b);

        function deliverBags(sortedPositions, bagCarryingLimit, shouldReturn) {
            let totalDistance = 0;

            if (!shouldReturn) {
                totalDistance -= sortedPositions[sortedPositions.length - 1];
            }

            // Pick next
            for (let positionIndex = sortedPositions.length - 1 ; positionIndex >= 0 ; positionIndex -= bagCarryingLimit) {
                totalDistance += sortedPositions[positionIndex] * 2;
            }
            return totalDistance;
        }

        if (positivePositions.length > 0 && negativePositions.length > 0) {
            let totalDeliveryDistance = 0;
            if (positivePositions[positivePositions.length - 1] >= negativePositions[negativePositions.length - 1]) {
                totalDeliveryDistance += deliverBags(negativePositions, bagLimit, true);
                totalDeliveryDistance += deliverBags(positivePositions, bagLimit, false);
                print(totalDeliveryDistance);
            } else {
                totalDeliveryDistance += deliverBags(positivePositions, bagLimit, true);
                totalDeliveryDistance += deliverBags(negativePositions, bagLimit, false);
                print(totalDeliveryDistance);
            }
        } else if (positivePositions.length > 0) {
            print(deliverBags(positivePositions, bagLimit, false));
        } else {
            print(deliverBags(negativePositions, bagLimit, false));
        }
    }
}

'use strict';

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();
    });

    main();
});

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

function print(...args) {
    console.log(...args);
}

function main() {
    const testCases = readline();

    for (let i = 0 ; i < testCases ; i++) {
        const [_, limit] = readline().split(" ");
        const bagLimit = parseInt(limit);
        const depotPositions = readline().split(" ").map(n => parseInt(n));

        const negativePositions = depotPositions.filter(n => n < 0).map(n => n * -1).sort((a, b) => a - b);
        const positivePositions = depotPositions.filter(n => n > 0).sort((a, b) => a - b);

        function deliverBags(sortedPositions, bagCarryingLimit, shouldReturn) {
            let totalDistance = 0;

            if (!shouldReturn) {
                totalDistance -= sortedPositions[sortedPositions.length - 1];
            }

            // Pick next
            for (let positionIndex = sortedPositions.length - 1 ; positionIndex >= 0 ; positionIndex -= bagCarryingLimit) {
                totalDistance += sortedPositions[positionIndex] * 2;
            }
            return totalDistance;
        }

        if (positivePositions.length > 0 && negativePositions.length > 0) {
            let totalDeliveryDistance = 0;
            if (positivePositions[positivePositions.length - 1] >= negativePositions[negativePositions.length - 1]) {
                totalDeliveryDistance += deliverBags(negativePositions, bagLimit, true);
                totalDeliveryDistance += deliverBags(positivePositions, bagLimit, false);
                print(totalDeliveryDistance);
            } else {
                totalDeliveryDistance += deliverBags(positivePositions, bagLimit, true);
                totalDeliveryDistance += deliverBags(negativePositions, bagLimit, false);
                print(totalDeliveryDistance);
            }
        } else if (positivePositions.length > 0) {
            print(deliverBags(positivePositions, bagLimit, false))
        } else {
            print(deliverBags(negativePositions, bagLimit, false))
        }
    }
}

'use strict';

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();
    });

    main();
});

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

function print(...args) {
    console.log(...args);
}

function main() {
    const testCases = readline();

    for (let i = 0 ; i < testCases ; i++) {
        const [_, bagLimit] = readline().split(" ");
        const depotPositions = readline().split(" ").map(n => parseInt(n));

        const negativePositions = depotPositions.filter(n => n < 0).map(n => n * -1).sort((a, b) => a - b);
        const positivePositions = depotPositions.filter(n => n > 0).sort((a, b) => a - b);

        function deliverBags(sortedPositions, bagCarryingLimit, shouldReturn) {
            let totalDistance = 0;

            // Pick next
            for (let positionIndex = sortedPositions.length - 1 ; positionIndex >= 0 ; positionIndex -= bagCarryingLimit) {
                totalDistance += sortedPositions[positionIndex] * 2;
            }

            if (!shouldReturn) {
                totalDistance -= sortedPositions[sortedPositions.length - 1];
            }
            return totalDistance;
        }

        if (positivePositions.length > 0 && negativePositions.length > 0) {
            let totalDeliveryDistance = 0;
            if (positivePositions[positivePositions.length - 1] >= negativePositions[negativePositions.length - 1]) {
                totalDeliveryDistance += deliverBags(negativePositions, parseInt(bagLimit), true);
                totalDeliveryDistance += deliverBags(positivePositions, parseInt(bagLimit), false);
                print(totalDeliveryDistance);
            } else {
                totalDeliveryDistance += deliverBags(positivePositions, parseInt(bagLimit), true);
                totalDeliveryDistance += deliverBags(negativePositions, parseInt(bagLimit), false);
                print(totalDeliveryDistance);
            }
        } else if (positivePositions.length > 0) {
            print(deliverBags(positivePositions, parseInt(bagLimit), false));
        } else {
            print(deliverBags(negativePositions, parseInt(bagLimit), false));
        }
    }
}

'use strict';

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();
    });

    main();
});

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

function print(...args) {
    console.log(...args);
}

function main() {
    const testCases = readline();

    for (let i = 0 ; i < testCases ; i++) {
        const [_, bagLimit] = readline().split(" ");
        const depotPositions = readline().split(" ").map(n => parseInt(n));

        const negativePositions = depotPositions.filter(n => n < 0).map(n => n * -1).sort((a, b) => a - b);
        const positivePositions = depotPositions.filter(n => n > 0).sort((a, b) => a - b);

        function deliverBags(sortedPositions, bagCarryingLimit, shouldReturn) {
            let totalDistance = 0;
            let previousPosition = 0;
            let totalCarryingBags = bagCarryingLimit;
            for (let positionIndex = 0 ; positionIndex < sortedPositions.length ; positionIndex++) {

                totalDistance += sortedPositions[positionIndex] - previousPosition;
                previousPosition = sortedPositions[positionIndex];

                totalCarryingBags--;

                if ((totalCarryingBags === 0 && positionIndex !== sortedPositions.length - 1) || (sortedPositions.length - (positionIndex + 1) === bagCarryingLimit)) {
                    totalDistance += previousPosition;
                    previousPosition = 0;
                    totalCarryingBags = bagCarryingLimit;
                }
            }

            if (shouldReturn && previousPosition !== 0) {
                totalDistance += previousPosition;
            }
            return totalDistance;
        }

        if (positivePositions.length > 0 && negativePositions.length > 0) {
            let totalDeliveryDistance = 0;
            if (positivePositions[positivePositions.length - 1] >= negativePositions[negativePositions.length - 1]) {
                totalDeliveryDistance += deliverBags(negativePositions, parseInt(bagLimit), true);
                totalDeliveryDistance += deliverBags(positivePositions, parseInt(bagLimit), false);
                print(totalDeliveryDistance);
            } else {
                totalDeliveryDistance += deliverBags(positivePositions, parseInt(bagLimit), true);
                totalDeliveryDistance += deliverBags(negativePositions, parseInt(bagLimit), false);
                print(totalDeliveryDistance);
            }
        } else if (positivePositions.length > 0) {
            print(deliverBags(positivePositions, parseInt(bagLimit), false));
        } else {
            print(deliverBags(negativePositions, parseInt(bagLimit), false));
        }
    }
}

var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

const INF = 1e9;

function main () {
	let T = rn();
	while (T--) {
		const [n, k] = rna();
		const x = rna();

		const pos = [], neg = [];
		for (const elm of x) {
			if (elm >= 0)
				pos.push(elm);
			else
				neg.push(-elm);
		}

		pos.sort((a, b) => a - b);
		neg.sort((a, b) => a - b);

		let ans = solve(pos) + solve(neg);
		//console.log({ans, pos, neg})
		ans -= Math.max(pos.length ? pos[pos.length - 1] : 0, neg.length ? neg[neg.length - 1] : 0);

		function solve(ar) {
			let res = 0;
			for (let i = 0; i < ar.length; i++) {
				if ((i + 1 - n % k) % k == 0 || i == ar.length - 1) {
					res += 2 * ar[i];
				}
			}
			return res;
		}

		console.log(ans);
	}
}

"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++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
function iInpArr1() {
  return readline()
    .trim()
    .split("")
    .map((cur) => parseInt(cur));
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const sqrt = (n) => {
  let low = 1n,
    high = n,
    ans;
  while (low <= high) {
    let mid = (low + high) / 2n;
    if (mid * mid <= n) {
      ans = mid;
      low = mid + 1n;
    } else high = mid - 1n;
  }
  return ans;
};

const solve = () => {
  let t = getValue();
  while (t--) {
    let [n, k] = iInpArr();
    let arr = iInpArr();
    let pos = [],
      neg = [];
    for (let i = 0; i < n; i++) {
      if (arr[i] < 0) neg.push(Math.abs(arr[i]));
      else pos.push(arr[i]);
    }
    let sum = 0,
      max1 = -Infinity,
      max2 = -Infinity;
    if (neg.length !== 0) {
      neg.sort((a, b) => b - a);
      max1 = neg[0];
      let j = 0;
      while (j < neg.length) {
        sum += neg[j] * 2;
        j += k;
      }
    }
    if (pos.length !== 0) {
      max2 = pos[0];
      pos.sort((a, b) => b - a);
      let j = 0;
      while (j < pos.length) {
        sum += pos[j] * 2;
        j += k;
      }
    }
    if (max1 > max2) sum -= neg[0];
    else sum -= pos[0];
    console.log(sum);
  }
};
solve();


'use strict';

function solve(n, a) {
  let min = -1,
      max = -1;
  for (let i = 0; i < n; i++) {
    if (a[0][i] === '*' || a[1][i] === '*') {
      if (min === -1) min = i;
      max = i;
    }
  }
  if (min === max) {
    if (a[0][min] === '*' && a[1][min] === '*') return 1;
    return 0;
  }
  let l = Array.from({
    length: n
  }, () => [0, 0]);
  if (a[0][min] === '*') l[min][1]++;
  if (a[1][min] === '*') l[min][0]++;
  for (let i = min + 1; i <= max; i++) {
    var _l;
    const tmp = ((_l = l[i - 1]) !== null && _l !== void 0 ? _l : [0, 0]).map(num => num + 1);
    if (a[0][i] === '*') tmp[1]++;
    if (a[1][i] === '*') tmp[0]++;
    l[i][0] = Math.min(tmp[0], tmp[1] + 1, l[i - 1][1] + 2);
    l[i][1] = Math.min(tmp[1], tmp[0] + 1, l[i - 1][0] + 2);
  }
  return Math.min(...l[max]);
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = Number(await read());
      const a = [];
      let tmp = 2;
      while (tmp--) {
        a.push(await read());
      }
      res[i] = solve(n, a);
    }
    return 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', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});

'use strict';

function solve(n, a) {
  let min = -1,
      max = -1;
  for (let i = 0; i < n; i++) {
    if (a[0][i] === '*' || a[1][i] === '*') {
      if (min === -1) min = i;
      max = i;
    }
  }
  if (min === max) {
    if (a[0][min] === '*' && a[1][min] === '*') return 1;
    return 0;
  }
  let dp = [0, 0];
  if (a[0][min] === '*') dp[1]++;
  if (a[1][min] === '*') dp[0]++;
  for (let i = min + 1; i <= max; i++) {
    const tmp = dp.map(num => num + 1);
    if (a[0][i] === '*') tmp[1]++;
    if (a[1][i] === '*') tmp[0]++;
    tmp[0] = Math.min(tmp[0], dp[1] + 2);
    tmp[1] = Math.min(tmp[1], dp[0] + 2);
    dp = tmp;
  }
  return Math.min(...dp);
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = Number(await read());
      const a = [];
      let tmp = 2;
      while (tmp--) {
        a.push(await read());
      }
      res[i] = solve(n, a);
    }
    return 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', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});

'use strict';

function solve(n, a) {
  let min = -1,
      max = -1;
  for (let i = 0; i < n; i++) {
    if (a[0][i] === '*' || a[1][i] === '*') {
      if (min === -1) min = i;
      max = i;
    }
  }
  if (min === max) {
    if (a[0][min] === '*' && a[1][min] === '*') return 1;
    return 0;
  }
  let l = Array.from({
    length: n
  }, () => [0, 0]);
  if (a[0][min] === '*') l[min][1]++;
  if (a[1][min] === '*') l[min][0]++;
  for (let i = min + 1; i <= max; i++) {
    var _l;
    const tmp = ((_l = l[i - 1]) !== null && _l !== void 0 ? _l : [0, 0]).map(num => num + 1);
    if (a[0][i] === '*') tmp[1]++;
    if (a[1][i] === '*') tmp[0]++;
    l[i][0] = Math.min(tmp[0], tmp[1] + 1, l[i - 1][1] + 2);
    l[i][1] = Math.min(tmp[1], tmp[0] + 1, l[i - 1][0] + 2);
  }
  let r = Array.from({
    length: n
  }, () => [0, 0]);
  if (a[0][max] === '*') r[max][1]++;
  if (a[1][max] === '*') r[max][0]++;
  for (let i = max - 1; i >= min; i--) {
    var _r;
    const tmp = ((_r = r[i + 1]) !== null && _r !== void 0 ? _r : [0, 0]).map(num => num + 1);
    if (a[0][i] === '*') tmp[1]++;
    if (a[1][i] === '*') tmp[0]++;
    r[i][0] = Math.min(tmp[0], tmp[1] + 1, r[i + 1][1] + 2);
    r[i][1] = Math.min(tmp[1], tmp[0] + 1, r[i + 1][0] + 2);
  }
  let res = Infinity;
  for (let i = min; i <= max; i++) {
    if (i < max) res = Math.min(res, l[i][0] + r[i + 1][0] + 1, l[i][1] + r[i + 1][1] + 1);else res = Math.min(res, l[i][0], l[i][1]);
  }
  return res;
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = Number(await read());
      const a = [];
      let tmp = 2;
      while (tmp--) {
        a.push(await read());
      }
      res[i] = solve(n, a);
    }
    return 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', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});

'use strict';
// HEADER:
const print = console.log;
let IS_MULTITEST, testN;
const pcalc = testN=>{
  let res = calc(testN);
  if (Array.isArray(res)){
    pa(res);
  } else if (Number.isFinite(res) || typeof res=='string'){
    print(res);
  }
};

const main = ()=>{
  if (IS_MULTITEST){
    let T = +readline()
    for (testN=1; testN<=T; testN++)
      pcalc(T);
  } else
   pcalc();
};

const lines = [];
const rl = require('readline').createInterface({
   input: process.stdin, output: process.stdout});
rl.on('line', line=>{
  lines.push(line);
});
rl.on('close', main);
let rli = 0;
const readline = ()=>lines[rli++];
const L = process.env.DEBUG ? console.log : ()=>{};
const LT = obj=>L(`Test #${testN}`, obj);

const ra = ()=>readline().split(' ').map(a=>+a)
const pa = arr=>print(arr.join(' '));

// SOLUTION:
IS_MULTITEST = 1;

const calc = ()=>{
  // READING:
  let [n] = ra();
  let S = [];
  S.push(readline())
  S.push(readline())
  LT('\n'+ S.join('\n'));
  // PROCESSING:
  let ans = 0;
  let l = 0;
  let r = n-1;
  let toNum = (pos)=>{
    if (S[0][pos]=='.' && S[1][pos]=='.')
      return 0;
    if (S[0][pos]=='*' && S[1][pos]=='*')
      return 3;
    if (S[0][pos]=='*')
      return 1;
    if (S[1][pos]=='*')
      return 2;
  }
  while (toNum(l)==0)
    l++;
  while (toNum(r)==0)
    r--;
  let lstate = toNum(l);
  if (lstate==3){
    ans++;
  }
  l++;
  while (l<=r){
    ans++;
    let nextL = toNum(l);
    if (nextL==0){
      l++;
      continue;
    }
    if (nextL==3){
      ans++;
      lstate = 3;
      l++;
      continue;
    }
    if (nextL==lstate || lstate==3){
      l++;
      lstate = nextL;
      continue;
    }
    ans++;
    l++;
    lstate = 3;
  }
  return ans;
};

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 = +lines[l++]
        const grid = lines.slice(l, l + 2).map(str => str.trim())
        l += 2
        output[i] = solve(n, grid)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, grid) {
    const p0 = Array(n)
    const p1 = Array(n)
    for (let i = 0; i < n; i++) {
        let now
        now = grid[0][i] === '*' ? 1 : 0
        p0[i] = i ? p0[i - 1] + now : now
        now = grid[1][i] === '*' ? 1 : 0
        p1[i] = i ? p1[i - 1] + now : now
    }
    const pre = []
    const suf = []
    for (let i = 0; i < n; i++) {
        pre[i] = []
        for (let j = 0; j < 2; j++) {
            if (i) {
                pre[i][j] = Math.min(
                    ((ok(grid, pre, i - 1, j) || grid[1 - j][i - 1] === '*') ? 1 : 0)
                        + pre[i - 1][j]
                        + (grid[1 - j][i - 1] === '*' ? 1 : 0),
                    ok(grid, pre, i - 1, 1 - j) ? pre[i - 1][1 - j] + 2 : (grid[j][i - 1] === '*' ? 1 : 0)
                )
            } else {
                pre[i][j] = 0
            }
        }
    }
    for (let i = n - 1; i >= 0; i--) {
        suf[i] = []
        for (let j = 0; j < 2; j++) {
            if (i < n - 1) {
                suf[i][j] = Math.min(
                    ((ok(grid, suf, i + 1, j) || grid[1 - j][i + 1] === '*') ? 1 : 0)
                        + suf[i + 1][j]
                        + (grid[1 - j][i + 1] === '*' ? 1 : 0),
                    ok(grid, suf, i + 1, 1 - j) ? suf[i + 1][1 - j] + 2 : (grid[j][i + 1] === '*' ? 1 : 0)
                )
            } else {
                suf[i][j] = 0
            }
        }
    }
    let ans = Infinity
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < 2; j++) {
            ans = Math.min(
                ans,
                get(n, pre, i, j) + get(n, suf, i, j) + (grid[1 - j][i] === '*' ? 1 : 0),
                get(n, pre, i, 1 - j) + get(n, suf, i, 1 - j) + 1,
            )
        }
    }
    // console.log(pre, suf)
    return ans
}
function ok(grid, dp, i, j) {
    return dp[i][j] > 0 || grid[j][i] === '*'
}
function get(n, dp, i, j) {
    if (i < 0 || i >= n) return 0
    return dp[i][j]
}

const lines = [];
const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });
rl.on('line', line => lines.push(line));
rl.on('close', main);
let rli = 0;
function readline() {
    return lines[rli++];
}

const ra = ()=>readline().split(' ').map(a=>+a);

/*---------------------------------------------------*/

const calc = ()=>{
    /* read */
    let n = +readline();
    let s0 = readline();
    let s1 = readline();

    let count = 0;
    let result = 0;

    for (let i = 0; i < n; i++) {
        if (s0[i] === '*') count++;
        if (s1[i] === '*') count++;
    }

    if (count === 1) return 0;

    let prev = -1;

    for (let i = 0; i < n; i++) {
        if (count === 1) return result;
        if (prev !== -1) {
            result++;
            if (s0[i] === '*' && s1[i] === '*') {
                result++;
                count -= 2;
                prev = 2;
            } else {
                if (s0[i] === '*' && prev === 1) {
                    result++;
                    count--;
                    prev = 2;
                } else if (s1[i] === '*' && prev === 0) {
                    result++;
                    count--;
                    prev = 2;
                } else if (s0[i] === '*' && prev === 0) {
                    count--;
                } else if (s1[i] === '*' && prev === 1) {
                    count--;
                } else if (s0[i] === '*' && prev === 2) {
                    count--;
                    prev = 0;
                } else if (s1[i] === '*' && prev === 2) {
                    count--;
                    prev = 1;
                }
            }
        } else {
            if (s0[i] === '*' && s1[i] === '*') {
                result++;
                count--;
                prev = 2;
            } else {
                if (s0[i] === '*') {
                    prev = 0;
                }
                if (s1[i] === '*') {
                    prev = 1;
                }
            }
        }
        // console.log(`DEBUG result ${result} count ${count} prev`, prev);
    }

    return count === 1 ? result : result + 1;

};

function main() {
    let T = +readline();
    let out = [];
    for (let t = 1; t <= T; t++){
        out.push(calc());
        // process.stdout.write(`${calc(n, a)}\n`);
    }
    process.stdout.write(out.join('\n')+'\n');
}

//import { readline, print } from '@ip-algorithmics/codeforces-io';
var t = +readline();
while (t--) {
    var n = +readline();
    var a = Array(2);
    a[0] = readline();
    a[1] = readline();
    var l0 = a[0].indexOf('*');
    var r0 = a[0].lastIndexOf('*');
    var l1 = a[1].indexOf('*');
    var r1 = a[1].lastIndexOf('*');
    if (l0 === -1)
        l0 = l1;
    if (l1 === -1)
        l1 = l0;
    var ans = 0;
    var cur = l0 < l1 ? 1 : l0 === l1 ? 2 : 0;
    for (var i = Math.min(l0, l1); i <= Math.max(r0, r1); i++) {
        if (a[0][i] === '*' && a[1][i] === '*') {
            ans++;
            cur = 2;
        }
        else if (a[0][i] === '*') {
            if (cur === 0) {
                ans++;
                cur = 2;
            }
            else
                cur = 1;
        }
        else if (a[1][i] === '*') {
            if (cur === 1) {
                ans++;
                cur = 2;
            }
            else
                cur = 0;
        }
        ans++;
    }
    print(ans - 1);
}

'use strict';

function solve(n, a) {
  let min = -1,
      max = -1;
  for (let i = 0; i < n; i++) {
    if (a[0][i] === '*' || a[1][i] === '*') {
      if (min === -1) min = i;
      max = i;
    }
  }
  if (min === max) {
    if (a[0][min] === '*' && a[1][min] === '*') return 1;
    return 0;
  }
  let l = Array.from({
    length: n
  }, () => [0, 0]);
  if (a[0][min] === '*') l[min][1]++;
  if (a[1][min] === '*') l[min][0]++;
  for (let i = min + 1; i <= max; i++) {
    var _l;
    const tmp = ((_l = l[i - 1]) !== null && _l !== void 0 ? _l : [0, 0]).map(num => num + 1);
    if (a[0][i] === '*') tmp[1]++;
    if (a[1][i] === '*') tmp[0]++;
    l[i][0] = Math.min(tmp[0], tmp[1] + 1);
    l[i][1] = Math.min(tmp[1], tmp[0] + 1);
  }
  let r = Array.from({
    length: n
  }, () => [0, 0]);
  if (a[0][max] === '*') r[max][1]++;
  if (a[1][max] === '*') r[max][0]++;
  for (let i = max - 1; i >= min; i--) {
    var _r;
    const tmp = ((_r = r[i + 1]) !== null && _r !== void 0 ? _r : [0, 0]).map(num => num + 1);
    if (a[0][i] === '*') tmp[1]++;
    if (a[1][i] === '*') tmp[0]++;
    r[i][0] = Math.min(tmp[0], tmp[1] + 1);
    r[i][1] = Math.min(tmp[1], tmp[0] + 1);
  }
  let res = Infinity;
  for (let i = min; i <= max; i++) {
    if (i < max) res = Math.min(res, l[i][0] + r[i + 1][0] + 1, l[i][1] + r[i + 1][1] + 1);else res = Math.min(res, l[i][0], l[i][1]);
  }
  return res;
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = Number(await read());
      const a = [];
      let tmp = 2;
      while (tmp--) {
        a.push(await read());
      }
      res[i] = solve(n, a);
    }
    return 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', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});

'use strict';

function solve(n, a) {
  let min = -1,
      max = -1;
  for (let i = 0; i < n; i++) {
    if (a[0][i] === '*' || a[1][i] === '*') {
      if (min === -1) min = i;
      max = i;
    }
  }
  if (min === max) {
    if (a[0][min] === '*' && a[1][min] === '*') return 1;
    return 0;
  }
  let dp = [0, 0];
  if (a[0][min] === '*') dp[1]++;
  if (a[1][min] === '*') dp[0]++;
  for (let i = min + 1; i <= max; i++) {
    const tmp = dp.map(num => num + 1);
    if (a[0][i] === '*') tmp[1]++;
    if (a[1][i] === '*') tmp[0]++;
    dp[0] = Math.min(tmp[0], tmp[1] + 1);
    dp[1] = Math.min(tmp[1], tmp[0] + 1);
  }
  let res = Math.min(...dp);
  {
    let dp = [0, 0];
    if (a[0][max] === '*') dp[1]++;
    if (a[1][max] === '*') dp[0]++;
    for (let i = max - 1; i >= min; i--) {
      const tmp = dp.map(num => num + 1);
      if (a[0][i] === '*') tmp[1]++;
      if (a[1][i] === '*') tmp[0]++;
      dp[0] = Math.min(tmp[0], tmp[1] + 1);
      dp[1] = Math.min(tmp[1], tmp[0] + 1);
    }
    res = Math.min(res, ...dp);
  }
  return res;
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = Number(await read());
      const a = [];
      let tmp = 2;
      while (tmp--) {
        a.push(await read());
      }
      res[i] = solve(n, a);
    }
    return 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', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});

'use strict';

function solve(n, a) {
  let min = -1,
      max = -1;
  for (let i = 0; i < n; i++) {
    if (a[0][i] === '*' || a[1][i] === '*') {
      if (min === -1) min = i;
      max = i;
    }
  }
  if (min === max) {
    if (a[0][min] === '*' && a[1][min] === '*') return 1;
    return 0;
  }
  let dp = [0, 0];
  if (a[0][min] === '*') dp[1]++;
  if (a[1][min] === '*') dp[0]++;
  for (let i = min + 1; i <= max; i++) {
    const tmp = dp.map(num => num + 1);
    if (a[0][i] === '*') tmp[1]++;
    if (a[1][i] === '*') tmp[0]++;
    dp[0] = Math.min(tmp[0], tmp[1] + 1);
    dp[1] = Math.min(tmp[1], tmp[0] + 1);
  }
  return Math.min(...dp);
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = Number(await read());
      const a = [];
      let tmp = 2;
      while (tmp--) {
        a.push(await read());
      }
      res[i] = solve(n, a);
    }
    return 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', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});

'use strict';
// HEADER:
const print = console.log;
let IS_MULTITEST, testN;
const pcalc = testN=>{
  let res = calc(testN);
  if (Array.isArray(res)){
    pa(res);
  } else if (Number.isFinite(res) || typeof res=='string'){
    print(res);
  }
};

const main = ()=>{
  if (IS_MULTITEST){
    let T = +readline()
    for (testN=1; testN<=T; testN++)
      pcalc(T);
  } else
   pcalc();
};

const lines = [];
const rl = require('readline').createInterface({
   input: process.stdin, output: process.stdout});
rl.on('line', line=>{
  lines.push(line);
});
rl.on('close', main);
let rli = 0;
const readline = ()=>lines[rli++];
const L = process.env.DEBUG ? console.log : ()=>{};
const LT = obj=>L(`Test #${testN}`, obj);

const ra = ()=>readline().split(' ').map(a=>+a)
const pa = arr=>print(arr.join(' '));

// SOLUTION:
IS_MULTITEST = 1;

const calc = ()=>{
  // READING:
  let [n] = ra();
  let S = [];
  S.push(readline())
  S.push(readline())
  LT('\n'+ S.join('\n'));
  // PROCESSING:
  let ans = 0;
  let l = 0;
  let r = n-1;
  let toNum = (pos)=>{
    if (S[0][pos]=='.' && S[1][pos]=='.')
      return 0;
    if (S[0][pos]=='*' && S[1][pos]=='*')
      return 3;
    if (S[0][pos]=='*')
      return 1;
    if (S[1][pos]=='*')
      return 2;
  }
  while (toNum(l)==0)
    l++;
  while (toNum(r)==0)
    r--;
  let lstate = toNum(l), rstate = toNum(r);
  if (l==r)
    return toNum(l)==3 ? 1 : 0;
  while (l<r){
    let nextL = toNum(l);
    let nextR = toNum(r);
    if (nextL==0){
      ans++;
      l++;
      continue;
    }
    if (nextR==0){
      ans++;
      r--;
      continue;
    }
    if (nextR==3){
      ans++;
      ans++;
      rstate = 3;
      r--;
      continue;
    }
    if (nextL==3){
      ans++;
      ans++;
      lstate = 3;
      l++;
      continue;
    }
    if (nextL==lstate){
      l++;
      ans++;
      continue;
    }
    if (nextR==rstate){
      r--;
      ans++;
      continue;
    }
    if (lstate==3){
      l++;
      ans++;
      continue;
    }
    if (rstate==3){
      r--;
      ans++;
      continue;
    }
    lstate = 3;
    l++;
    ans++;
    ans++;
  }

  if (toNum(l)<3)
  if ((lstate==3 || rstate==3) || lstate==rstate && lstate==toNum(l))
    return ans;
  return ans+1;
};

'use strict';
// HEADER:
const print = console.log;
let IS_MULTITEST, testN;
const pcalc = testN=>{
  let res = calc(testN);
  if (Array.isArray(res)){
    pa(res);
  } else if (Number.isFinite(res) || typeof res=='string'){
    print(res);
  }
};

const main = ()=>{
  if (IS_MULTITEST){
    let T = +readline()
    for (testN=1; testN<=T; testN++)
      pcalc(T);
  } else
   pcalc();
};

const lines = [];
const rl = require('readline').createInterface({
   input: process.stdin, output: process.stdout});
rl.on('line', line=>{
  lines.push(line);
});
rl.on('close', main);
let rli = 0;
const readline = ()=>lines[rli++];
const L = process.env.DEBUG ? console.log : ()=>{};
const LT = obj=>L(`Test #${testN}`, obj);

const ra = ()=>readline().split(' ').map(a=>+a)
const pa = arr=>print(arr.join(' '));

// SOLUTION:
IS_MULTITEST = 1;

const calc = ()=>{
  // READING:
  let [n] = ra();
  let S = [];
  S.push(readline())
  S.push(readline())
  LT('\n'+ S.join('\n'));
  // PROCESSING:
  let ans = 0;
  let l = 0;
  let r = n-1;
  let toNum = (pos)=>{
    if (S[0][pos]=='.' && S[1][pos]=='.')
      return 0;
    if (S[0][pos]=='*' && S[1][pos]=='*')
      return 3;
    if (S[0][pos]=='*')
      return 1;
    if (S[1][pos]=='*')
      return 2;
  }
  while (toNum(l)==0)
    l++;
  while (toNum(r)==0)
    r--;
  let lstate = toNum(l), rstate = toNum(r);
  if (l==r)
    return toNum(l)==3 ? 1 : 0;
  while (l<r){
    let nextL = toNum(l);
    let nextR = toNum(r);
    if (nextL==0){
      ans++;
      l++;
      continue;
    }
    if (nextR==0){
      ans++;
      r--;
      continue;
    }
    if (nextR==3){
      ans++;
      ans++;
      rstate = 3;
      r--;
      continue;
    }
    if (nextL==3){
      ans++;
      ans++;
      lstate = 3;
      l++;
      continue;
    }
    if (nextL==lstate){
      l++;
      ans++;
      continue;
    }
    if (nextR==rstate){
      r--;
      ans++;
      continue;
    }
    if (lstate==3){
      l++;
      ans++;
      continue;
    }
    if (rstate==3){
      r--;
      ans++;
      continue;
    }
    lstate = 3;
    l++;
    ans++;
    ans++;
  }

  if (lstate==3 || rstate==3 || lstate==rstate && lstate==toNum(l))
    return ans;
  return ans+1;
};

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 = +lines[l++]
        const grid = lines.slice(l, l + 2).map(str => str.trim())
        l += 2
        output[i] = solve(n, grid)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, grid) {
    const p0 = Array(n)
    const p1 = Array(n)
    for (let i = 0; i < n; i++) {
        let now
        now = grid[0][i] === '*' ? 1 : 0
        p0[i] = i ? p0[i - 1] + now : now
        now = grid[1][i] === '*' ? 1 : 0
        p1[i] = i ? p1[i - 1] + now : now
    }
    const pre = []
    const suf = []
    for (let i = 0; i < n; i++) {
        pre[i] = []
        for (let j = 0; j < 2; j++) {
            if (i) {
                pre[i][j] = Math.min(
                    pre[i - 1][j] + 1 + (grid[1 - j][i - 1] === '*' ? 1 : 0),
                    pre[i - 1][1 - j] + 2
                )
            } else {
                pre[i][j] = 0
            }
        }
    }
    for (let i = n - 1; i >= 0; i--) {
        suf[i] = []
        for (let j = 0; j < 2; j++) {
            if (i < n - 1) {
                suf[i][j] = Math.min(
                    suf[i + 1][j] + 1 + (grid[1 - j][i + 1] === '*' ? 1 : 0),
                    suf[i + 1][1 - j] + 2
                )
            } else {
                suf[i][j] = 0
            }
        }
    }
    let ans = Infinity
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < 2; j++) {
            ans = Math.min(
                ans,
                get(n, pre, i, j) + get(n, suf, i, j) + (grid[1 - j][i] === '*' ? 1 : 0),
                get(n, pre, i, 1 - j) + get(n, suf, i, 1 - j) + 1,
            )
        }
    }
    // console.log(pre, suf)
    return ans
}
function get(n, dp, i, j) {
    if (i < 0 || i >= n) return 0
    return dp[i][j]
}

const lines = [];
const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });
rl.on('line', line => lines.push(line));
rl.on('close', main);
let rli = 0;
function readline() {
    return lines[rli++];
}

const ra = ()=>readline().split(' ').map(a=>+a);

/*---------------------------------------------------*/

const calc = ()=>{
    /* read */
    let n = +readline();
    let s0 = readline();
    let s1 = readline();

    let count = 0;
    let result = 0;

    for (let i = 0; i < n; i++) {
        if (s0[i] === '*') count++;
        if (s1[i] === '*') count++;
    }

    if (count === 1) return 0;

    let prev = -1;

    for (let i = 0; i < n; i++) {
        if (count === 1) return result;
        if (prev !== -1) {
            result++;
            if (s0[i] === '*' && s1[i] === '*') {
                result++;
                count -= 2;
                prev = 2;
            } else {
                if (s0[i] === '*' && prev === 1) {
                    result++;
                    count--;
                    prev = 2;
                }
                if (s1[i] === '*' && prev === 0) {
                    result++;
                    count--;
                    prev = 2;
                }
                if (s0[i] === '*' && prev === 0) {
                    count--;
                }
                if (s1[i] === '*' && prev === 1) {
                    count--;
                }
            }
        } else {
            if (s0[i] === '*' && s1[i] === '*') {
                result++;
                count--;
                prev = 2;
            } else {
                if (s0[i] === '*') {
                    prev = 0;
                }
                if (s1[i] === '*') {
                    prev = 1;
                }
            }
        }

    }

    return result;

};

function main() {
    let T = +readline();
    let out = [];
    for (let t = 1; t <= T; t++){
        out.push(calc());
        // process.stdout.write(`${calc(n, a)}\n`);
    }
    process.stdout.write(out.join('\n')+'\n');
}

//import { readline, print } from '@ip-algorithmics/codeforces-io';
var t = +readline();
while (t--) {
    var n = +readline();
    var a = Array(2);
    a[0] = readline();
    a[1] = readline();
    var l0 = a[0].indexOf('*');
    var r0 = a[0].lastIndexOf('*');
    var l1 = a[1].indexOf('*');
    var r1 = a[1].lastIndexOf('*');
    if (l0 === -1)
        l0 = l1;
    if (l1 === -1)
        l1 = l0;
    var ans = 0;
    var cur = l0 < l1 ? 1 : l0 === l1 ? 2 : 0;
    for (var i = Math.min(l0, l1); i <= Math.max(r0, r1); i++) {
        if (a[0][i] === '*' && a[1][i] === '*') {
            ans++;
            cur = 2;
        }
        else if (a[0][i] === '*') {
            if (cur === 0) {
                ans++;
                cur = 2;
            }
        }
        else if (a[1][i] === '*') {
            if (cur === 1) {
                ans++;
                cur = 2;
            }
        }
        ans++;
    }
    print(ans - 1);
}

//import { readline, print } from '@ip-algorithmics/codeforces-io';
var t = +readline();
while (t--) {
    var n = +readline();
    var a = Array(2);
    a[0] = readline();
    a[1] = readline();
    var l0 = a[0].indexOf('*');
    var r0 = a[0].lastIndexOf('*');
    var l1 = a[1].indexOf('*');
    var r1 = a[1].lastIndexOf('*');
    if (l0 === -1)
        l0 = l1;
    if (l1 === -1)
        l1 = l0;
    var ans = 0;
    var cur = 2;
    for (var i = Math.min(l0, l1); i < Math.max(r0, r1); i++) {
        if (a[0][i] === '*' && a[1][i] === '*') {
            ans++;
            cur = 2;
        }
        else if (a[0][i] === '*') {
            if (cur === 0)
                ans++;
            cur = 1;
        }
        else if (a[1][i] === '*') {
            if (cur === 1)
                ans++;
            cur = 0;
        }
        ans++;
    }
    if (r0 === r1) {
        ans++;
    }
    print(ans);
}

//import { readline, print } from '@ip-algorithmics/codeforces-io';
var t = +readline();
while (t--) {
    var n = +readline();
    var a = Array(3);
    a[1] = readline();
    a[2] = readline();
    var l1 = a[1].indexOf('*');
    var r1 = a[1].lastIndexOf('*');
    var l2 = a[2].indexOf('*');
    var r2 = a[2].lastIndexOf('*');
    if (l1 === -1) {
        print(r2 - l2);
        continue;
    }
    if (l2 === -1) {
        print(r1 - l1);
        continue;
    }
    var ans = 0;
    if (r1 >= l2 && r2 >= l1) {
        ans = (r1 - l1) + (r2 - l2) + 1;
    }
    else {
        ans = Math.max(r1, r2) - Math.min(l1, l2) + 1;
    }
    print(ans);
}