The Cereal Guy's friend Serial Guy likes to watch soap operas. An episode is about to start, and he hasn't washed his plate yet. But he decided to at least put in under the tap to be filled with water. The plate can be represented by a parallelepiped k × n × m, that is, it has k layers (the first layer is the upper one), each of which is a rectangle n × m with empty squares ('.') and obstacles ('#'). The water can only be present in the empty squares. The tap is positioned above the square (x, y) of the first layer, it is guaranteed that this square is empty. Every minute a cubical unit of water falls into the plate. Find out in how many minutes the Serial Guy should unglue himself from the soap opera and turn the water off for it not to overfill the plate. That is, you should find the moment of time when the plate is absolutely full and is going to be overfilled in the next moment.Note: the water fills all the area within reach (see sample 4). Water flows in each of the 6 directions, through faces of 1 × 1 × 1 cubes.

The first line contains three numbers k, n, m (1 ≤ k, n, m ≤ 10) which are the sizes of the plate. Then follow k rectangles consisting of n lines each containing m characters '.' or '#', which represents the "layers" of the plate in the order from the top to the bottom. The rectangles are separated by empty lines (see the samples). The last line contains x and y (1 ≤ x ≤ n, 1 ≤ y ≤ m) which are the tap's coordinates. x is the number of the line and y is the number of the column. Lines of each layer are numbered from left to right by the integers from 1 to n, columns of each layer are numbered from top to bottom by the integers from 1 to m.

The answer should contain a single number, showing in how many minutes the plate will be filled.


You are given a permutation $$$p=[p_1, p_2, \ldots, p_n]$$$ of integers from $$$1$$$ to $$$n$$$. Let's call the number $$$m$$$ ($$$1 \le m \le n$$$) beautiful, if there exists two indices $$$l, r$$$ ($$$1 \le l \le r \le n$$$), such that the numbers $$$[p_l, p_{l+1}, \ldots, p_r]$$$ is a permutation of numbers $$$1, 2, \ldots, m$$$.For example, let $$$p = [4, 5, 1, 3, 2, 6]$$$. In this case, the numbers $$$1, 3, 5, 6$$$ are beautiful and $$$2, 4$$$ are not. It is because:  if $$$l = 3$$$ and $$$r = 3$$$ we will have a permutation $$$[1]$$$ for $$$m = 1$$$;  if $$$l = 3$$$ and $$$r = 5$$$ we will have a permutation $$$[1, 3, 2]$$$ for $$$m = 3$$$;  if $$$l = 1$$$ and $$$r = 5$$$ we will have a permutation $$$[4, 5, 1, 3, 2]$$$ for $$$m = 5$$$;  if $$$l = 1$$$ and $$$r = 6$$$ we will have a permutation $$$[4, 5, 1, 3, 2, 6]$$$ for $$$m = 6$$$;  it is impossible to take some $$$l$$$ and $$$r$$$, such that $$$[p_l, p_{l+1}, \ldots, p_r]$$$ is a permutation of numbers $$$1, 2, \ldots, m$$$ for $$$m = 2$$$ and for $$$m = 4$$$. You are given a permutation $$$p=[p_1, p_2, \ldots, p_n]$$$. For all $$$m$$$ ($$$1 \le m \le n$$$) determine if it is a beautiful number or not.

The first line contains the only integer $$$t$$$ ($$$1 \le t \le 1000$$$)  — the number of test cases in the input. The next lines contain the description of test cases. The first line of a test case contains a number $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the given permutation $$$p$$$. The next line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \le p_i \le n$$$, all $$$p_i$$$ are different) — the given permutation $$$p$$$. It is guaranteed, that the sum of $$$n$$$ from all test cases in the input doesn't exceed $$$2 \cdot 10^5$$$.

Print $$$t$$$ lines — the answers to test cases in the order they are given in the input.  The answer to a test case is the string of length $$$n$$$, there the $$$i$$$-th character is equal to $$$1$$$ if $$$i$$$ is a beautiful number and is equal to $$$0$$$ if $$$i$$$ is not a beautiful number.

NoteThe first test case is described in the problem statement.In the second test case all numbers from $$$1$$$ to $$$5$$$ are beautiful:  if $$$l = 3$$$ and $$$r = 3$$$ we will have a permutation $$$[1]$$$ for $$$m = 1$$$;  if $$$l = 3$$$ and $$$r = 4$$$ we will have a permutation $$$[1, 2]$$$ for $$$m = 2$$$;  if $$$l = 2$$$ and $$$r = 4$$$ we will have a permutation $$$[3, 1, 2]$$$ for $$$m = 3$$$;  if $$$l = 2$$$ and $$$r = 5$$$ we will have a permutation $$$[3, 1, 2, 4]$$$ for $$$m = 4$$$;  if $$$l = 1$$$ and $$$r = 5$$$ we will have a permutation $$$[5, 3, 1, 2, 4]$$$ for $$$m = 5$$$.

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

var arr = ''
process.stdin.on('data', (i) => {
  arr += i
})

process.stdin.on('end', () => {
  arr = arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  const t = parseInt(arr.shift())

  for(let j = 0; j < t; j++) {
    const n = parseInt(arr[2 * j])
    let min, max, s = new Array(n)
    let pos = {}
    const arrN = arr[2 * j +  1].split(' ').map((a, i) => {
      a = parseInt(a)
      pos[a] = i
      return parseInt(a)
    })
    max = min = pos[1]
    s[0] = s[n - 1] = 1

    for(let i = 1, num = 2; i < n - 1; i++, num ++) {
      max = Math.max(max, pos[num])
      min = Math.min(min, pos[num])
      if(max - min + 1  == num) s[i] = 1
      else s[i] = 0
    }

    console.log(s.join(''))
  }
})


Polycarp's workday lasts exactly $$$n$$$ minutes. He loves chocolate bars and can eat one bar in one minute. Today Polycarp has $$$k$$$ bars at the beginning of the workday.In some minutes of the workday Polycarp has important things to do and in such minutes he is not able to eat a chocolate bar. In other minutes he can either eat or not eat one chocolate bar. It is guaranteed, that in the first and in the last minutes of the workday Polycarp has no important things to do and he will always eat bars in this minutes to gladden himself at the begining and at the end of the workday. Also it is guaranteed, that $$$k$$$ is strictly greater than $$$1$$$.Your task is to determine such an order of eating chocolate bars that the maximum break time between eating bars is as minimum as possible.Consider that Polycarp eats a bar in the minute $$$x$$$ and the next bar in the minute $$$y$$$ ($$$x < y$$$). Then the break time is equal to $$$y - x - 1$$$ minutes. It is not necessary for Polycarp to eat all bars he has.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 200\,000$$$, $$$2 \le k \le n$$$) — the length of the workday in minutes and the number of chocolate bars, which Polycarp has in the beginning of the workday. The second line contains the string with length $$$n$$$ consisting of zeros and ones. If the $$$i$$$-th symbol in the string equals to zero, Polycarp has no important things to do in the minute $$$i$$$ and he can eat a chocolate bar. In the other case, Polycarp is busy in the minute $$$i$$$ and can not eat a chocolate bar. It is guaranteed, that the first and the last characters of the string are equal to zero, and Polycarp always eats chocolate bars in these minutes.

Print the minimum possible break in minutes between eating chocolate bars.

NoteIn the first example Polycarp can not eat the chocolate bar in the second minute, so the time of the break equals to one minute.In the second example Polycarp will eat bars in the minutes $$$1$$$ and $$$8$$$ anyway, also he needs to eat the chocolate bar in the minute $$$5$$$, so that the time of the maximum break will be equal to $$$3$$$ minutes.

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

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


You are given a string A. Find a string B, where B is a palindrome and A is a subsequence of B.A subsequence of a string is a string that can be derived from it by deleting some (not necessarily consecutive) characters without changing the order of the remaining characters. For example, "cotst" is a subsequence of "contest".A palindrome is a string that reads the same forward or backward.The length of string B should be at most 104. It is guaranteed that there always exists such string.You do not need to find the shortest answer, the only restriction is that the length of string B should not exceed 104.

First line contains a string A (1 ≤ |A| ≤ 103) consisting of lowercase Latin letters, where |A| is a length of A.

Output single line containing B consisting of only lowercase Latin letters. You do not need to find the shortest answer, the only restriction is that the length of string B should not exceed 104. If there are many possible B, print any of them.

NoteIn the first example, "aba" is a subsequence of "aba" which is a palindrome.In the second example, "ab" is a subsequence of "aabaa" which is a palindrome.

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

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

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


Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number n. How many times can Gerald put a spell on it until the number becomes one-digit?

The first line contains the only integer n (0 ≤ n ≤ 10100000). It is guaranteed that n doesn't contain any leading zeroes.

Print the number of times a number can be replaced by the sum of its digits until it only contains one digit.

NoteIn the first sample the number already is one-digit — Herald can't cast a spell.The second test contains number 10. After one casting of a spell it becomes 1, and here the process is completed. Thus, Gerald can only cast the spell once.The third test contains number 991. As one casts a spell the following transformations take place: 991 → 19 → 10 → 1. After three transformations the number becomes one-digit.

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

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

/* 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;
}

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


You are given a complete directed graph $$$K_n$$$ with $$$n$$$ vertices: each pair of vertices $$$u \neq v$$$ in $$$K_n$$$ have both directed edges $$$(u, v)$$$ and $$$(v, u)$$$; there are no self-loops.You should find such a cycle in $$$K_n$$$ that visits every directed edge exactly once (allowing for revisiting vertices).We can write such cycle as a list of $$$n(n - 1) + 1$$$ vertices $$$v_1, v_2, v_3, \dots, v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1$$$ — a visiting order, where each $$$(v_i, v_{i + 1})$$$ occurs exactly once.Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists.Since the answer can be too large print its $$$[l, r]$$$ segment, in other words, $$$v_l, v_{l + 1}, \dots, v_r$$$.

The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. The first and only line of each test case contains three integers $$$n$$$, $$$l$$$ and $$$r$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le l \le r \le n(n - 1) + 1$$$, $$$r - l + 1 \le 10^5$$$) — the number of vertices in $$$K_n$$$, and segment of the cycle to print. It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$ and the total sum of $$$r - l + 1$$$ doesn't exceed $$$10^5$$$.

For each test case print the segment $$$v_l, v_{l + 1}, \dots, v_r$$$ of the lexicographically smallest cycle that visits every edge exactly once.

NoteIn the second test case, the lexicographically minimum cycle looks like: $$$1, 2, 1, 3, 2, 3, 1$$$.In the third test case, it's quite obvious that the cycle should start and end in vertex $$$1$$$.

let i = '';
let lines;
process.stdin.on('data', (c) => (i += c));
process.stdin.on('end', () => {
  const { EOL } = require('os');
  lines = i.split(EOL); /*your input text, split by lines*/
  main();
});

function solve(n, l, r) {
  let start = Math.ceil(l / 2);
  let k = 1;
  while (start > n - k) {
    start -= (n - k);
    ++k;
    if (k === n) break;
  }
  const result = [];
  let current = start + k;
  while (result.length < r - l + 3) {
    if (k === n) {
      result.push(1);
      break;
    }
    result.push(k);
    result.push(current);
    if (current === n) {
      ++k;
      current = k;
    }
    ++current;
  }
  const odd = (l + 1) % 2;
  return result.slice(odd, odd + r - l + 1).join(' ');
}

function main() {
  let currentLine = 0;
  const readLine = (_) => lines[currentLine++].split(' ').map((val) => parseInt(val));

  const test = readLine()[0];
  for (let t = 1; t <= test; ++t) {
    const [n, l, r] = readLine();
    console.log(solve(n, l, r));
  }
}


Polycarp is currently developing a project in Vaja language and using a popular dependency management system called Vamen. From Vamen's point of view both Vaja project and libraries are treated projects for simplicity.A project in Vaja has its own uniqie non-empty name consisting of lowercase latin letters with length not exceeding 10 and version — positive integer from 1 to 106. Each project (keep in mind that it is determined by both its name and version) might depend on other projects. For sure, there are no cyclic dependencies.You're given a list of project descriptions. The first of the given projects is the one being developed by Polycarp at this moment. Help Polycarp determine all projects that his project depends on (directly or via a certain chain). It's possible that Polycarp's project depends on two different versions of some project. In this case collision resolving is applied, i.e. for each such project the system chooses the version that minimizes the distance from it to Polycarp's project. If there are several options, the newer (with the maximum version) is preferred. This version is considered actual; other versions and their dependencies are ignored.More formal, choose such a set of projects of minimum possible size that the following conditions hold:   Polycarp's project is chosen;  Polycarp's project depends (directly or indirectly) on all other projects in the set;  no two projects share the name;  for each project x that some other project in the set depends on we have either x or some y with other version and shorter chain to Polycarp's project chosen. In case of ties the newer one is chosen. Output all Polycarp's project's dependencies (Polycarp's project itself should't be printed) in lexicographical order.

The first line contains an only integer n (1 ≤ n ≤ 1 000) — the number of projects in Vaja. The following lines contain the project descriptions. Each project is described by a line consisting of its name and version separated by space. The next line gives the number of direct dependencies (from 0 to n - 1) and the dependencies themselves (one in a line) in arbitrary order. Each dependency is specified by its name and version. The projects are also given in arbitrary order, but the first of them is always Polycarp's. Project descriptions are separated by one empty line. Refer to samples for better understanding. It's guaranteed that there are no cyclic dependencies.

Output all Polycarp's project's dependencies in lexicographical order.

9
codehorses 5
3
webfrmk 6
mashadb 1
mashadb 2

commons 2
0

mashadb 3
0

webfrmk 6
2
mashadb 3
commons 2

extra 4
1
extra 3

extra 3
0

extra 1
0

mashadb 1
1
extra 3

mashadb 2
1
extra 1

NoteThe first sample is given in the pic below. Arrow from A to B means that B directly depends on A. Projects that Polycarp's project «a» (version 3) depends on are painted black.  The second sample is again given in the pic below. Arrow from A to B means that B directly depends on A. Projects that Polycarp's project «codehorses» (version 5) depends on are paint it black. Note that «extra 1» is chosen instead of «extra 3» since «mashadb 1» and all of its dependencies are ignored due to «mashadb 2».

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


A total of $$$n$$$ depots are located on a number line. Depot $$$i$$$ lies at the point $$$x_i$$$ for $$$1 \le i \le n$$$.You are a salesman with $$$n$$$ bags of goods, attempting to deliver one bag to each of the $$$n$$$ depots. You and the $$$n$$$ bags are initially at the origin $$$0$$$. You can carry up to $$$k$$$ bags at a time. You must collect the required number of goods from the origin, deliver them to the respective depots, and then return to the origin to collect your next batch of goods.Calculate the minimum distance you need to cover to deliver all the bags of goods to the depots. You do not have to return to the origin after you have delivered all the bags.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10\,500$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2 \cdot 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$x_1, x_2, \ldots, x_n$$$ ($$$-10^9 \le x_i \le 10^9$$$). It is possible that some depots share the same position. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a single integer denoting the minimum distance you need to cover to deliver all the bags of goods to the depots.

NoteIn the first test case, you can carry only one bag at a time. Thus, the following is a solution sequence that gives a minimum travel distance: $$$0 \to 2 \to 0 \to 4 \to 0 \to 3 \to 0 \to 1 \to 0 \to 5$$$, where each $$$0$$$ means you go the origin and grab one bag, and each positive integer means you deliver the bag to a depot at this coordinate, giving a total distance of $$$25$$$ units. It must be noted that there are other sequences that give the same distance.In the second test case, you can follow the following sequence, among multiple such sequences, to travel minimum distance: $$$0 \to 6 \to 8 \to 7 \to 0 \to 5 \to 4 \to 3 \to 0 \to (-5) \to (-10) \to (-15)$$$, with distance $$$41$$$. It can be shown that $$$41$$$ is the optimal distance for this test case.

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

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

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

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

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])
}

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


You are given a board of size $$$2 \times n$$$ ($$$2$$$ rows, $$$n$$$ columns). Some cells of the board contain chips. The chip is represented as '*', and an empty space is represented as '.'. It is guaranteed that there is at least one chip on the board.In one move, you can choose any chip and move it to any adjacent (by side) cell of the board (if this cell is inside the board). It means that if the chip is in the first row, you can move it left, right or down (but it shouldn't leave the board). Same, if the chip is in the second row, you can move it left, right or up.If the chip moves to the cell with another chip, the chip in the destination cell disappears (i. e. our chip captures it).Your task is to calculate the minimum number of moves required to leave exactly one chip on the board.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the board. The second line of the test case contains the string $$$s_1$$$ consisting of $$$n$$$ characters '*' (chip) and/or '.' (empty cell). The third line of the test case contains the string $$$s_2$$$ consisting of $$$n$$$ characters '*' (chip) and/or '.' (empty cell). Additional constraints on the input:   in each test case, there is at least one chip on a board;  the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print one integer — the minimum number of moves required to leave exactly one chip on the board.

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


Ashish has an array $$$a$$$ of size $$$n$$$.A subsequence of $$$a$$$ is defined as a sequence that can be obtained from $$$a$$$ by deleting some elements (possibly none), without changing the order of the remaining elements.Consider a subsequence $$$s$$$ of $$$a$$$. He defines the cost of $$$s$$$ as the minimum between:   The maximum among all elements at odd indices of $$$s$$$.  The maximum among all elements at even indices of $$$s$$$. Note that the index of an element is its index in $$$s$$$, rather than its index in $$$a$$$. The positions are numbered from $$$1$$$. So, the cost of $$$s$$$ is equal to $$$min(max(s_1, s_3, s_5, \ldots), max(s_2, s_4, s_6, \ldots))$$$.For example, the cost of $$$\{7, 5, 6\}$$$ is $$$min( max(7, 6), max(5) ) = min(7, 5) = 5$$$.Help him find the minimum cost of a subsequence of size $$$k$$$.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \leq k \leq n \leq 2 \cdot 10^5$$$)  — the size of the array $$$a$$$ and the size of the subsequence. The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$)  — the elements of the array $$$a$$$.

Output a single integer  — the minimum cost of a subsequence of size $$$k$$$.

NoteIn the first test, consider the subsequence $$$s$$$ = $$$\{1, 3\}$$$. Here the cost is equal to $$$min(max(1), max(3)) = 1$$$.In the second test, consider the subsequence $$$s$$$ = $$$\{1, 2, 4\}$$$. Here the cost is equal to $$$min(max(1, 4), max(2)) = 2$$$.In the fourth test, consider the subsequence $$$s$$$ = $$$\{3, 50, 2, 4\}$$$. Here the cost is equal to $$$min(max(3, 2), max(50, 4)) = 3$$$.

process.stdin.resume();
process.stdin.setEncoding('utf-8');
var input = '';
process.stdin.on('data', function (line) {
    input += line;
});
process.stdin.on('end', function () {
    var lines = input.split('\n');
    var _a = lineToNumArray(lines.shift()), n = _a[0], k = _a[1];
    var arr = lineToNumArray(lines.shift());
    console.log(Math.min(binarySearch(n, k, arr, 0), binarySearch(n, k, arr, 1)));
});
function binarySearch(n, k, arr, parity) {
    var lo = 1, hi = Math.max.apply(Math, arr);
    var ans;
    while (lo <= hi) {
        var mid = Math.floor((lo + hi) / 2);
        var count = 0;
        for (var i = 0; i < n && count < k; i++) {
            if (count % 2 === parity) {
                count += Number(arr[i] <= mid);
            }
            else {
                count++;
            }
        }
        if (count === k) {
            ans = mid;
            hi = mid - 1;
        }
        else {
            lo = mid + 1;
        }
    }
    return ans;
}
// input helper
function lineToNumArray(line) {
    return line.split(' ').map(function (element) { return parseInt(element, 10); });
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');
let input = '';
process.stdin.on('data', (line) => {
    input += line;
});
process.stdin.on('end', () => {
    const lines = input.split('\n');
    const [n, k] = lineToNumArray(lines.shift());
    const arr = lineToNumArray(lines.shift());
    console.log(Math.min(binarySearch(n, k, arr, 0), binarySearch(n, k, arr, 1)));
});
function binarySearch(n, k, arr, parity) {
    let lo = 1, hi = Math.max(...arr);
    let ans;
    while (lo <= hi) {
        const mid = Math.floor((lo + hi) / 2);
        let count = 0;
        for (let i = 0; i < n && count < k; i++) {
            if (count % 2 === parity) {
                count += Number(arr[i] <= mid);
            }
            else {
                count++;
            }
        }
        if (count === k) {
            ans = mid;
            hi = mid - 1;
        }
        else {
            lo = mid + 1;
        }
    }
    return ans;
}
// input helper
function lineToNumArray(line) {
    return line.split(' ').map(element => parseInt(element, 10));
}

nk = readline().split(" ").map(Number)
n = nk[0]
k = nk[1]
a=readline().split(" ").map(Number)

st=1
end=1000000000
while (st<=end) {
    mid=(st+end)>>1
    ct=0;i=1;pos=n
    if (k%2!==0) pos-=1
    while (i<pos) {
        if (a[i]<=mid) {
            ct+=1
            i+=1
        }
        i+=1
    }
    if (ct>=k>>1) {
        end=mid-1
        continue;
    }
    ct=0;i=0;pos=n
    if (k%2===0) pos-=1
    while (i<pos) {
        if(a[i]<=mid) {
            ct+=1
            i+=1
        }
        i+=1
    }
    if (ct>=(k+1)>>1) {
        end=mid-1
        continue;
    }
    st=mid+1
}
print (end+1)

nk = readline().split(" ").map(Number);
n = nk[0];
k = nk[1];
a=readline().split(" ").map(Number);

st=1
end=100000000
while (st<=end) {
    mid=(st+end)>>1
    ct=0;i=1;pos=n
    if (k%2!==0) pos-=1
    while (i<pos) {
        if (a[i]<=mid) {
            ct+=1
            i+=1
        }
        i+=1
    }
    if (ct>=k/2) {
        end=mid-1
        continue;
    }
    ct=0;i=0;pos=n
    if (k%2===0) pos-=1
    while (i<pos) {
        if(a[i]<=mid) {
            ct+=1
            i+=1
        }
        i+=1
    }
    if (ct>=(k+1)/2) {
        end=mid-1
        continue;
    }
    st=mid+1
}
print (end+1)

nk = readline().split(" ").map(Number)
n = nk[0]
k = nk[1]
a=readline().split(" ").map(Number)

st=1
end=1000000000
while (st<=end) {
    mid=(st+end)>>1
    ct=0;i=1;pos=n
    if (k%2!==0) pos-=1
    while (i<pos) {
        if (a[i]<=mid) {
            ct+=1
            i+=1
        }
        i+=1
    }
    if (ct>=k/2) {
        end=mid-1
        continue;
    }
    ct=0;i=0;pos=n
    if (k%2===0) pos-=1
    while (i<pos) {
        if(a[i]<=mid) {
            ct+=1
            i+=1
        }
        i+=1
    }
    if (ct>=(k+1)>>1) {
        end=mid-1
        continue;
    }
    st=mid+1
}
print (end+1)