Polycarp wants to cook a soup. To do it, he needs to buy exactly $$$n$$$ liters of water.There are only two types of water bottles in the nearby shop — $$$1$$$-liter bottles and $$$2$$$-liter bottles. There are infinitely many bottles of these two types in the shop.The bottle of the first type costs $$$a$$$ burles and the bottle of the second type costs $$$b$$$ burles correspondingly.Polycarp wants to spend as few money as possible. Your task is to find the minimum amount of money (in burles) Polycarp needs to buy exactly $$$n$$$ liters of water in the nearby shop if the bottle of the first type costs $$$a$$$ burles and the bottle of the second type costs $$$b$$$ burles. You also have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. The next $$$q$$$ lines contain queries. The $$$i$$$-th query is given as three space-separated integers $$$n_i$$$, $$$a_i$$$ and $$$b_i$$$ ($$$1 \le n_i \le 10^{12}, 1 \le a_i, b_i \le 1000$$$) — how many liters Polycarp needs in the $$$i$$$-th query, the cost (in burles) of the bottle of the first type in the $$$i$$$-th query and the cost (in burles) of the bottle of the second type in the $$$i$$$-th query, respectively.

Print $$$q$$$ integers. The $$$i$$$-th integer should be equal to the minimum amount of money (in burles) Polycarp needs to buy exactly $$$n_i$$$ liters of water in the nearby shop if the bottle of the first type costs $$$a_i$$$ burles and the bottle of the second type costs $$$b_i$$$ burles.

(function() {
    var read = {
        number: function() {
            return +readline();
        },
        arr: function(divider) {
            return readline().split(divider ? divider : '');
        },
        arrNumber: function(divider) {
            return readline()
                .split(divider ? divider : '')
                .map(item => +item);
        }
    }

    var q = read.number();

    for(var i = 0; i < q; i++) {
        var n = read.arrNumber(' ');

        if(n[0] === 1) {
            print(n[1]);
        }
        else if(n[1] * 2 > n[2]) {
            var h2 = Math.floor(n[0] / 2);
            print(h2 * n[2] + (n[0] - (h2 * 2)) * n[1]);
        }
        else {
            print(n[1] * n[0]);
        }
    }
}());

var n=parseInt(readline());
for(var i=0;i<n;i++)
{
  var s=readline().split(' ');
  if(s[0]%2==0)
  print(Math.min(s[0]*s[1],(s[0]/2)*s[2]));
  else
  print(Math.min(s[0]*s[1],Math.floor(s[0]/2)*s[2]+parseInt(s[1])));
}

var q = readline().split(" ").map(function(x) { return parseInt(x); })[0];
while (q-->0) {
	var numbers = readline().split(" ").map(function(x) { return parseInt(x); });
	var n = numbers[0], a = numbers[1], b = numbers[2];
	var down = 0, up = Math.floor(n/2) + 1;
	while (up > down + 5) {
		var t1 = down + Math.floor((up-down)/3);
		var cost1 = t1 * b + Math.max(0, n-t1*2) * a;
		var t2 = down + 2*Math.floor((up-down)/3);
		var cost2 = t2 * b + Math.max(0, n-t2*2) * a;
		if (cost1 < cost2) up = t2;
		else down = t1;
	}
	var mn = n*a;
	for (var t=down-50; t<=down+50; t++)
		if (t >= 0 && t*2 <= n) {
			var cost1 = t * b + Math.max(0, n-t*2) * a;
			mn = Math.min(mn, cost1);
		}
	write(mn + "\n");
}

var q = parseInt(readline())

for(var t=0;t<q;t++) {

    var nab = readline().split(' ').map((v)=>(parseInt(v)))
    var n = nab[0];
    var a = nab[1];
    var b = nab[2];

    var aa = (n%2) * a + parseInt(n/2) * b;
    var bb = n*a

    print( Math.min(aa, bb) )
}

var n = parseInt(readline());
for (var i = 0; i < n; i++) {
    var s = readline().split(" ");
    print(foo(s[0], s[1], s[2]));
}

function foo(n, a, b) {
    if (a*2 <= b) return n*a;
    return Math.trunc(n / 2) * b + n % 2* a;
}

function repeat(n, fn) {
    var result = [];
    for (var i = 0; i < n; i++)
        result.push(fn(i));
    return result;
}
function readInput(_a) {
    var line = _a.line, int = _a.int, ints = _a.ints, strings = _a.strings;
    var n = int();
    return { n: n, queries: repeat(n, function () { var _a = ints(), n = _a[0], a = _a[1], b = _a[2]; return { n: n, a: a, b: b }; }) };
}
function printOutput(result, _a) {
    var line = _a.line;
    result.forEach(function (r) { return line(r); });
}
function show(input) {
    console.log(input, '-->', solve(input));
}
function inputFunctions(line) {
    return {
        line: line,
        int: function () { return parseInt(line()); },
        strings: function () { return line().split(' '); },
        ints: function () { return line().split(' ').map(function (v) { return parseInt(v); }); }
    };
}
function outputFunctions(line) {
    return { line: line };
}
function sampleInput(input) {
    var lines = input.split('\n');
    var index = 0;
    var line = function () { return lines[index++]; };
    return inputFunctions(line);
}
function sample(input) {
    show(readInput(sampleInput(input)));
}
function run() {
    var input = readInput(inputFunctions(readline));
    var output = solve(input);
    printOutput(output, outputFunctions(print));
}
function solve(_a) {
    // implementation
    var n = _a.n, queries = _a.queries;
    return queries.map(function (_a) {
        var n = _a.n, a = _a.a, b = _a.b;
        if (a * 2 < b)
            return n * a;
        return n % 2 * a + (n - n % 2) / 2 * b;
    });
}
// sample(`4
// 10 1 3
// 7 3 2
// 1 1000 1
// 1000000000000 42 88`)
run();

function calc(n, a, b) {
  if (a <= b / 2) {
    return a * n;
  } else {
    return b * Math.floor(n / 2) + a * (n % 2);
  }
}

var q = parseInt(readline());
// print(q);
var nab;
for (var i = 0; i < q; i++) {
  nab = readline().split(" ").map(el => parseInt(el));
  // print(nab);
  print(calc(nab[0], nab[1], nab[2]));
}

var q=parseInt(readline());
for(var i=0;i<q;i++)
{
  var n=readline().split(' ');
  if(n[1]*2<=n[2])
  print(n[0]*n[1]);
  else
  {
    if(n[0]%2==0)
    print(n[2]*Math.floor((n[0]/2)));
    else
    {
      print(n[2]*Math.floor((n[0]/2))+parseInt(n[1]));
    }
  }
}

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

  let tmp=0, T=0, triplets=[];

  rl.on('line', (input) => {
      if (tmp==0) {T=Number(input); tmp++;}
      else {
          if (tmp<=T){
          let str=input.split(' ').map(a=>{return Number(a);});
            triplets.push(str);
            tmp++;}
          }
    if (tmp>T){ rl.close(); therest();}
    return 0;}
);

let therest=function() {
    for (let i=0; i<T; i++) {
        let n=triplets[i][0], a=triplets[i][1], b=triplets[i][2];
       // console.log(n, a, b);

        if (2*a<=b) console.log(a*n);
        else if (n%2==0) console.log(b*n/2);
        else console.log(a+b*(n-1)/2);

    }
//console.log(T, pairs)
}
//console.log(lngth, str);}

  /*
  rl.question('What do you think of Node.js? ', (answer) => {
    // TODO: Log the answer in a database
    console.log(`Thank you for your valuable feedback: ${answer}`);

    rl.close();
  });*/

function main() {
    for(var i = 1; i < data.length; i++){
        var x = data[i].split(" ").map(x=>parseInt(x));
        console.log(Math.min(x[1]*2, x[2])*Math.floor(x[0]/2)+x[0]%2*x[1])
    }
}
const readline = require('readline');
const rl = readline.createInterface({input: process.stdin});
var data = [];
rl.on('line', function (line) {data.push(line);});
rl.on('close', main);

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

rl.on('line', (d) => {
  if (c === 0) {
    c++;
    return;
  }

  let [n, a, b] = d.split(' ').map(Number);
  let ans = 0;

  if (n === 1) {
    ans += a;
  }
  else {
    if (a * 2 < b) {
      ans += n * a;
    }
    else {
      ans += Math.floor(n / 2) * b;
      if (n % 2 === 1) {
        ans += a;
      }
    }
  }

  console.log(ans);
  c++;
});

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

rl.on('line', (d) => {
  if (c === 0) {
    c++;
    return;
  }

  let [n, a, b] = d.split(' ').map(Number);
  const ans = Math.floor(n / 2) * Math.min(2*a, b) + n % 2 * a;

  // if (n === 1) {
  //   ans += a;
  // }
  // else {
  //   if (a * 2 < b) {
  //     ans += n * a;
  //   }
  //   else {
  //     ans += Math.floor(n / 2) * b;
  //     if (n % 2 === 1) {
  //       ans += a;
  //     }
  //   }
  // }

  console.log(ans);
  c++;
});

var n=parseInt(readline());
for(var i=0;i<n;i++)
{
  var s=readline().split(' ');
  if(s[0]%2==0)
  print(Math.min(s[0]*s[1],(s[0]/2)*s[2]));
  else
  print(Math.min(s[0]*s[1],Math.floor(s[0]/2)*s[2]+s[1]));
}

var n=parseInt(readline());
for(var i=0;i<n;i++)
{
  var s=readline().split(' ');
  if(s[0]%2===0)
  print(Math.min(s[0]*s[1],(s[0]/2)*s[2]));
  else
  print(Math.min(s[0]*s[1],Math.floor(s[0]/2)*s[2]+s[1]));
}

var n=parseInt(readline());
for(var i=0;i<n;i++)
{
  var s=readline().split(' ');
  if(s[0]%2==0)
  print(Math.min(s[0]*s[1],(s[0]/2)*s[2]));
  else
  {
    print(Math.min(s[0]*s[1],Math.floor(s[0]/2)*s[2]+s[1]));
    print(s[0]*s[1],Math.floor(s[0]/2));
  }
}

var n=parseInt(readline());
for(var i=0;i<n;i++)
{
  var s=readline().split(' ');
  if(parseInt(s[0])%2==0)
  print(Math.min(s[0]*s[1],(s[0]/2)*s[2]));
  else
  print(Math.min(s[0]*s[1],(Math.floor(s[0]/2)*s[2]+s[1])));
}

var n=parseInt(readline());
for(var i=0;i<n;i++)
{
  var s=readline().split(' ');
  if(parseInt(s[0])%2==0)
  print(Math.min(s[0]*s[1],(s[0]/2)*s[2]));
  else
  print(Math.min(s[0]*s[1],Math.floor(s[0]/2)*s[2]+s[1]));
}

var n=parseInt(readline());
for(var i=0;i<n;i++)
{
  var s=readline().split(' ');
  if(s[0]%2==0)
  print(Math.min(s[0]*s[1],(s[0]/2)*s[2]));
  else
  {
    print(Math.min(s[0]*s[1],Math.floor(s[0]/2)*s[2]+s[1]));
    print(2);
  }
}

var n = parseInt(readline());
for (var i = 0; i < n; i++) {
    var s = readline().split(" ");
    print(foo(s[0], s[1], s[2]));
}

function foo(n, a, b) {
    if (a*2 <= b) return n*a;
    return Math.ceil(n / 2) * b + (n % 2) * a;
}


There is a house with $$$n$$$ flats situated on the main street of Berlatov. Vova is watching this house every night. The house can be represented as an array of $$$n$$$ integer numbers $$$a_1, a_2, \dots, a_n$$$, where $$$a_i = 1$$$ if in the $$$i$$$-th flat the light is on and $$$a_i = 0$$$ otherwise.Vova thinks that people in the $$$i$$$-th flats are disturbed and cannot sleep if and only if $$$1 < i < n$$$ and $$$a_{i - 1} = a_{i + 1} = 1$$$ and $$$a_i = 0$$$.Vova is concerned by the following question: what is the minimum number $$$k$$$ such that if people from exactly $$$k$$$ pairwise distinct flats will turn off the lights then nobody will be disturbed? Your task is to find this number $$$k$$$.

The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 100$$$) — the number of flats in the house. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$a_i \in \{0, 1\}$$$), where $$$a_i$$$ is the state of light in the $$$i$$$-th flat.

Print only one integer — the minimum number $$$k$$$ such that if people from exactly $$$k$$$ pairwise distinct flats will turn off the light then nobody will be disturbed.

NoteIn the first example people from flats $$$2$$$ and $$$7$$$ or $$$4$$$ and $$$7$$$ can turn off the light and nobody will be disturbed. It can be shown that there is no better answer in this example.There are no disturbed people in second and third examples.

function solve(values) {
    var indexes = [];
    for (var i = 1; i < values.length - 1; i++) {
        if (values[i] === 0 && values[i - 1] === 1 && values[i + 1] === 1) {
            indexes.push(i);
        }
    }

    var counter = 0;
    for (var _i = 0; _i < indexes.length; _i++) {
        if (indexes[_i + 1] != null && indexes[_i] + 2 === indexes[_i + 1]) {
            counter++;
            _i += 1;
            continue;
        }
        counter++;
    }

    return counter;
}

readline()
var numbers = readline().split(" ").map(function(x) { return parseInt(x); });
write(solve(numbers))

readline();
var rooms = readline().split(' ');
var cnt = 0;
for(var i = 2; i < rooms.length; i++) {
    if(rooms[i] - rooms[i - 1] === 1 && rooms[i - 2] === '1') {
        rooms[i++] = '0';
        cnt++;
    }
}
print(cnt);

readline();
var arr = readline().split(" ");
var disturbed = 0;
for(var i = 1; i < arr.length - 1; i++){
    if(arr[i - 1] == 1 && arr[i + 1] == 1 && arr[i] == 0){
        disturbed++;
        arr[i - 1] = arr[i + 1] = 0;
    }
}
print(disturbed);


One day Vasya painted a Cartesian coordinate system on a piece of paper and marked some set of points (x1, y1), (x2, y2), ..., (xn, yn). Let's define neighbors for some fixed point from the given set (x, y):   point (x', y') is (x, y)'s right neighbor, if x' > x and y' = y  point (x', y') is (x, y)'s left neighbor, if x' < x and y' = y  point (x', y') is (x, y)'s lower neighbor, if x' = x and y' < y  point (x', y') is (x, y)'s upper neighbor, if x' = x and y' > y We'll consider point (x, y) from the given set supercentral, if it has at least one upper, at least one lower, at least one left and at least one right neighbor among this set's points.Vasya marked quite many points on the paper. Analyzing the picture manually is rather a challenge, so Vasya asked you to help him. Your task is to find the number of supercentral points in the given set.

The first input line contains the only integer n (1 ≤ n ≤ 200) — the number of points in the given set. Next n lines contain the coordinates of the points written as "x y" (without the quotes) (|x|, |y| ≤ 1000), all coordinates are integers. The numbers in the line are separated by exactly one space. It is guaranteed that all points are different.

Print the only number — the number of supercentral points of the given set.

NoteIn the first sample the supercentral points are only points (1, 1) and (1, 2).In the second sample there is one supercental point — point (0, 0).

;(function () {

	var n = +readline();

	var p = [];
	for (var i = 0; i < n; i++) {
		var e = readline().split(' ');
		p.push( {x: +e[0], y: +e[1]} );
	}

	var s = 0;
	for (var i = 0; i < n; i++) {
		var f = false;

		for (var j = 0; j < n; j++)
			if (p[i].x == p[j].x && p[i].y > p[j].y) {
				f = true;
				break;
			}

		if (f) {
			f = false;
			for (var j = 0; j < n; j++)
				if (p[i].x == p[j].x && p[i].y < p[j].y) {
					f = true;
					break;
				}

			if (f) {
				f = false;
				for (var j = 0; j < n; j++)
					if (p[i].y == p[j].y && p[i].x > p[j].x) {
						f = true;
						break;
					}

				if (f) {
					f = false;
					for (var j = 0; j < n; j++)
						if (p[i].y == p[j].y && p[i].x < p[j].x) {
							f = true;
							break;
						}

					if (f) s++;
				}
			}
		}
	}

	print(s);

}).call(this);

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}
function main() {
  let t = +readLine();
  let count = 0;
  const arr = [];
  while (t--) {
    let [x, y] = readLine()
      .split(" ")
      .map((n) => parseInt(n));
    arr.push([x, y]);
  }

  for (let i = 0; i < arr.length; i++) {
    const [x, y] = arr[i];
    let [left, right, top, bottom] = [0, 0, 0, 0];
    for (let j = 0; j < arr.length; j++) {
      if (i !== j) {
        const [cx, cy] = arr[j];
        if (cx < x && cy === y) left++;
        if (cx > x && cy === y) right++;
        if (cx === x && cy > y) top++;
        if (cx === x && cy < y) bottom++;
      }
    }
    if (left > 0 && right > 0 && top > 0 && bottom > 0) count++;
  }
  console.log(count);
}

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

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

function isPrime(x) {
	let s = Math.sqrt(x);
	let i = 2;
	while (i <= s) {
		if (x % i === 0) {
			return false;
		}
		i++;
	}
	return true;
}

function isSuperCentral(cord, xs, ys) {
	let [x, y] = cord;
	let minY = Math.min(...xs[x]),
		maxY = Math.max(...xs[x]),
		minX = Math.min(...ys[y]),
		maxX = Math.max(...ys[y]);
	return minY < y && maxY > y && minX < x && maxX > x;
}

function main() {
	let n = readLine() >> 0;
	let chart = [];
	let xs = {},
		ys = {};
	while (n--) {
		let [x, y] = readLine()
			.split(' ')
			.map(x => x >> 0);
		xs[x] = xs[x] || [];
		xs[x].push(y);
		ys[y] = ys[y] || [];
		ys[y].push(x);
		chart.push([x, y]);
	}
	let c = 0;
	for (let i = 0; i < chart.length; ++i)
		if (isSuperCentral(chart[i], xs, ys)) c++;

	console.log(c);
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', (inputStd) => {
    inputString += inputStd;
});
process.stdin.on('end', function () {
    inputString = inputString
        .trim()
        .split('\n')
        .map((str) => {
            return str.trim();
        });
    main();
});
function readLine() {
    return inputString[currentLine++];
}

function main() {
    let n = parseInt(readLine());
    let Allx = [];
    let Ally = [];
    for (let i = 0; i < n; i++) {
        let [x, y] = readLine().split(' ').map(Number);
        Allx.push(x);
        Ally.push(y);
    }

    let up = [];
    let down = [];
    let left = [];
    let right = [];

    for (let i = 0; i < Allx.length; i++) {
        for (let j = 0; j < n; j++) {
            if (Allx[i] === Allx[j] && Ally[i] > Ally[j]) {
                down[i] = true;
            } else if (Allx[i] === Allx[j] && Ally[i] < Ally[j]) {
                up[i] = true;
            } else if (Allx[i] > Allx[j] && Ally[i] === Ally[j]) {
                left[i] = true;
            } else if (Allx[i] < Allx[j] && Ally[i] === Ally[j]) {
                right[i] = true;
            }
        }
    }
    let count = 0;
    for (let i = 0; i < n; i++) {
        if (
            up[i] === true &&
            left[i] === true &&
            right[i] === true &&
            down[i] === true
        ) {
            count++;
        }
    }
    console.log(count);
}


So the Beautiful Regional Contest (BeRC) has come to an end! $$$n$$$ students took part in the contest. The final standings are already known: the participant in the $$$i$$$-th place solved $$$p_i$$$ problems. Since the participants are primarily sorted by the number of solved problems, then $$$p_1 \ge p_2 \ge \dots \ge p_n$$$.Help the jury distribute the gold, silver and bronze medals. Let their numbers be $$$g$$$, $$$s$$$ and $$$b$$$, respectively. Here is a list of requirements from the rules, which all must be satisfied:  for each of the three types of medals, at least one medal must be awarded (that is, $$$g>0$$$, $$$s>0$$$ and $$$b>0$$$);  the number of gold medals must be strictly less than the number of silver and the number of bronze (that is, $$$g<s$$$ and $$$g<b$$$, but there are no requirements between $$$s$$$ and $$$b$$$);  each gold medalist must solve strictly more problems than any awarded with a silver medal;  each silver medalist must solve strictly more problems than any awarded a bronze medal;  each bronze medalist must solve strictly more problems than any participant not awarded a medal;  the total number of medalists $$$g+s+b$$$ should not exceed half of all participants (for example, if $$$n=21$$$, then you can award a maximum of $$$10$$$ participants, and if $$$n=26$$$, then you can award a maximum of $$$13$$$ participants). The jury wants to reward with medals the total maximal number participants (i.e. to maximize $$$g+s+b$$$) so that all of the items listed above are fulfilled. Help the jury find such a way to award medals.

The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of a test case contains an integer $$$n$$$ ($$$1 \le n \le 4\cdot10^5$$$) — the number of BeRC participants. The second line of a test case contains integers $$$p_1, p_2, \dots, p_n$$$ ($$$0 \le p_i \le 10^6$$$), where $$$p_i$$$ is equal to the number of problems solved by the $$$i$$$-th participant from the final standings. The values $$$p_i$$$ are sorted in non-increasing order, i.e. $$$p_1 \ge p_2 \ge \dots \ge p_n$$$. The sum of $$$n$$$ over all test cases in the input does not exceed $$$4\cdot10^5$$$.

Print $$$t$$$ lines, the $$$j$$$-th line should contain the answer to the $$$j$$$-th test case. The answer consists of three non-negative integers $$$g, s, b$$$.   Print $$$g=s=b=0$$$ if there is no way to reward participants with medals so that all requirements from the statement are satisfied at the same time.  Otherwise, print three positive numbers $$$g, s, b$$$ — the possible number of gold, silver and bronze medals, respectively. The sum of $$$g+s+b$$$ should be the maximum possible. If there are several answers, print any of them.

NoteIn the first test case, it is possible to reward $$$1$$$ gold, $$$2$$$ silver and $$$3$$$ bronze medals. In this case, the participant solved $$$5$$$ tasks will be rewarded with the gold medal, participants solved $$$4$$$ tasks will be rewarded with silver medals, participants solved $$$2$$$ or $$$3$$$ tasks will be rewarded with bronze medals. Participants solved exactly $$$1$$$ task won't be rewarded. It's easy to see, that in this case, all conditions are satisfied and it is possible to reward participants in this way. It is impossible to give more than $$$6$$$ medals because the number of medals should not exceed half of the number of participants. The answer $$$1$$$, $$$3$$$, $$$2$$$ is also correct in this test case.In the second and third test cases, it is impossible to reward medals, because at least one medal of each type should be given, but the number of medals should not exceed half of the number of participants.

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])
    const arrN = arr[2 * j +  1].split(' ').map(a => parseInt(a))

    let g, s, b
    g = s = b = 0
    g ++
    let gDone = false
    let sDone = false
    let half = Math.floor(n / 2)
    let bBeforeChange = 0

    for(let i = 1; i < half; i++) {
      // console.log(bBeforeChange, arrN[i])
      if(arrN[i] == arrN[i - 1]) {
        if(!gDone) g++
        else if(!sDone) s++
        else {
          if(i == half - 1 && arrN[i] == arrN[i + 1]) b = bBeforeChange
          else b++
        }
      }
      else {
        if(!gDone) {
          gDone = true
          s++
        }
        else if(!sDone && s > g) {
          sDone = true
          b++
        }
        else if(!sDone) {
          s++
        }
        else {
          bBeforeChange = b
          if(!(i == half - 1 && arrN[i] == arrN[i + 1])) b++
        }
      }
      // console.log(i, g, s, b, gDone, sDone)
    }
    // console.log(g, s, b)
    if(n < 6) console.log('0 0 0')
    else if(g < b) console.log(`${g} ${s} ${b}`)
    else console.log('0 0 0')
  }
})

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])
    const arrN = arr[2 * j +  1].split(' ').map(a => parseInt(a))

    let g, s, b
    g = s = b = 0
    g ++
    let gDone = false
    let sDone = false
    let half = Math.floor(n / 2)
    let bBeforeChange = 0

    for(let i = 1; i < half; i++) {
      if(arrN[i] == arrN[i - 1]) {
        if(!gDone) g++
        else if(!sDone) s++
        else {
          if(i == half - 1 && arrN[i] == arrN[i + 1]) b = bBeforeChange
          else b++
        }
      }
      else {
        if(!gDone) {
          gDone = true
          s++
        }
        else if(!sDone && s > g) {
          sDone = true
          b++
        }
        else if(!sDone) {
          s++
        }
        else {
          bBeforeChange = b
          b++
        }
      }
      // console.log(i, g, s, b, gDone, sDone)
    }
    // console.log(g, s, b)
    if(g < b) console.log(`${g} ${s} ${b}`)
    else console.log('0 0 0')
  }
})

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])
    const arrN = arr[2 * j +  1].split(' ').map(a => parseInt(a))

    let g, s, b
    g = s = b = 0
    g ++
    let gDone = false
    let sDone = false
    let half = Math.floor(n / 2)
    let bBeforeChange = 0

    for(let i = 1; i < half; i++) {
      // console.log(bBeforeChange, arrN[i])
      if(arrN[i] == arrN[i - 1]) {
        if(!gDone) g++
        else if(!sDone) s++
        else {
          if(i == half - 1 && arrN[i] == arrN[i + 1]) b = bBeforeChange
          else b++
        }
      }
      else {
        if(!gDone) {
          gDone = true
          s++
        }
        else if(!sDone && s > g) {
          sDone = true
          b++
        }
        else if(!sDone) {
          s++
        }
        else {
          bBeforeChange = b
          if(!(i == half - 1 && arrN[i] == arrN[i + 1])) b++
        }
      }
      // console.log(i, g, s, b, gDone, sDone)
    }
    // console.log(g, s, b)
    if(n < 6) console.log('0 0 0 0')
    else if(g < b) console.log(`${g} ${s} ${b}`)
    else console.log('0 0 0')
  }
})


You are given an integer $$$n$$$. In $$$1$$$ move, you can do one of the following actions:  erase any digit of the number (it's acceptable that the number before the operation has exactly one digit and after the operation, it is "empty");  add one digit to the right. The actions may be performed in any order any number of times.Note that if, after deleting some digit from a number, it will contain leading zeroes, they will not be deleted. E.g. if you delete from the number $$$301$$$ the digit $$$3$$$, the result is the number $$$01$$$ (not $$$1$$$).You need to perform the minimum number of actions to make the number any power of $$$2$$$ (i.e. there's an integer $$$k$$$ ($$$k \ge 0$$$) such that the resulting number is equal to $$$2^k$$$). The resulting number must not have leading zeroes.E.g. consider $$$n=1052$$$. The answer is equal to $$$2$$$. First, let's add to the right one digit $$$4$$$ (the result will be $$$10524$$$). Then let's erase the digit $$$5$$$, so the result will be $$$1024$$$ which is a power of $$$2$$$.E.g. consider $$$n=8888$$$. The answer is equal to $$$3$$$. Let's erase any of the digits $$$8$$$ three times. The result will be $$$8$$$ which is a power of $$$2$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n \le 10^9$$$).

For each test case, output in a separate line one integer $$$m$$$ — the minimum number of moves to transform the number into any power of $$$2$$$.

NoteThe answer for the first test case was considered above.The answer for the second test case was considered above.In the third test case, it's enough to add to the right the digit $$$4$$$ — the number $$$6$$$ will turn into $$$64$$$.In the fourth test case, let's add to the right the digit $$$8$$$ and then erase $$$7$$$ and $$$5$$$ — the taken number will turn into $$$8$$$.The numbers of the fifth and the sixth test cases are already powers of two so there's no need to make any move.In the seventh test case, you can delete first of all the digit $$$3$$$ (the result is $$$01$$$) and then the digit $$$0$$$ (the result is $$$1$$$).

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 len = n => n.toString().length;

function sbsql (a, n) {
	a = a.toString();
	n = n.toString();

	let i = 0, j = 0;
	while (i < a.length && j < n.length) {
		if (n[j] == a[i]) i++;
		j++;
	}
	return i;
}

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

		let ans = len(n) + 1;
		let k = 1n;
		while (k < 1e18) {
			if (l = sbsql(k, n)) {
				ans = Math.min(ans, len(n) - l + len(k) - l);
			}
			k = k << 1n;
		}

		console.log(ans);
	}
}

'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++];
}

var maxN = 2 * 1e5 + 10
var mod = BigInt(1e9 + 7)

function main() {
  const xx = readline();
  var array = []
  var res = 1n
  var i =0
  while (i < 200) {
    array.push(res.toString())
    res = res* 2n
    i++
  }
  // console.log(array)
  Array(Number(xx)).fill(1).map((t, i) => {
    var string = readline();
    //
    // var [a, b, c] = readline().split(' ').map((x, iii) => {
    //   return parseInt(x)
    // })
    // console.log(string)
    var min = 10
    for (let j = 0; j < array.length; j++) {

      var same = 0
      var add = 0
      var result = true
      var exist = false
      for (let k = 0; k < array[j].length; k++) {
        exist = false
        for (let i = k + add; i < string.length; i++) {
          if (string[i] === array[j][k]) {
            same++;
            exist = true
            add = i - k
            break
          }
        }
        if (!exist) break
      }
      min = Math.min((string.length +array[j].length) - 2*same, min)
      // console.log(same, array[j], string, min)
    }
    +
    console.log(min)
  })
}

"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;
};
let p2 = [];
p2[0] = 1;
p2[1] = 2;
for (let i = 2; i < 70; i++) p2[i] = p2[i - 1] * 2;
for (let i = 0; i < 70; i++) {
  let j = p2[i],
    arr = [];
  while (j > 0) {
    arr.push(j % 10);
    j = Math.floor(j / 10);
  }
  p2[i] = arr.reverse();
}
const solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    let arr = [];
    while (n > 0) {
      arr.push(n % 10);
      n = Math.floor(n / 10);
    }
    arr.reverse();
    const helper = (arr1) => {
      let k = 0,
        op = 0,
        i = 0;
      while (k < arr.length && i < arr1.length) {
        if (arr[k] === arr1[i]) {
          op++;
          i++;
        }
        k++;
      }
      return arr.length - op + (arr1.length - op);
    };
    let ans = Infinity;
    for (let i = 0; i < p2.length; i++) {
      ans = Math.min(ans, helper(p2[i]));
    }
    console.log(ans);
  }
};
solve();

const readline = require("readline");
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});
const input = [];
const P2LIM = BigInt(2e18);

rl.on("line", (line) => {
  input.push(line);
});
rl.on("close", () => {
  const list = input.slice(1);
  const ts = [];
  for (let p2 = 1n; p2 <= P2LIM; p2 *= 2n) ts.push(String(p2));
  for (let e of list) {
    let res = e.length + 1;
    for (let p2 of ts) {
      res = Math.min(res, solve(e, p2));
    }
    console.log(res);
  }
});

function solve(s, t) {
  let tp = 0;
  let sp = 0;
  let taken = 0;

  while (sp < s.length && tp < t.length) {
    if (s[sp] === t[tp]) {
      taken++;
      tp++;
    }
    sp++;
  }
  return s.length - taken + t.length - taken;
}

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++]
    for (let i = 0; i < t; i++) {
        const n = +lines[l++]
        console.log(solve(n))
    }
// })()
})

function solve(n) {
    let target = 1n
    let min = 11
    for (let i = 0; i <= 70; i++) {
        const cur = cal(n, target)
        min = Math.min(min, cur)
        target += target
    }
    return min
}
function cal(n, target) {
    const a = String(n)
    const b = String(target)

    let i = 0
    let j = 0
    while (i < a.length && j < b.length) {
        if (a[i] === b[j]) {
            i++
            j++
        } else {
            i++
        }
    }
    const k = j
    const used = a.length - k
    return a.length - used + used - k + b.length - k

    const limit = Math.pow(2, a.length)
    let min = a.length + b.length
    for (let i = 0; i < limit; i++) {
        const r = []
        let used = 0
        let mask = 1
        for (let j = 0; j < a.length; j++) {
            if (i & mask) {
                used++
                r.push(a[j])
            }
            mask += mask
        }
        const p = r.join('')
        let k = 0
        for (; k < p.length; k++) {
            if (p[k] !== b[k]) break
        }
        min = Math.min(min, a.length - used + used - k + b.length - k)
    // console.log(p, b, used, k, a.length - used + b.length - k)
    }
    // console.log(a, b, min)
    // console.log('--')
    return min
}

let inputs = []

function read() {
    return inputs.pop();
}

function readInt() {
    return parseInt(read());
}

function solve() {
    let test = readInt();
    while (test--) {
        let n = read();
        let res = 100;
        let p2 = BigInt(1);
        for (let i = 0; i < 100; i++) {
            let s2 = p2.toString();
            let cost = 0;
            let ptr = 0;
            for (let i = 0; i < s2.length; i++) {
                while (ptr < n.length && n[ptr] != s2[i]) {
                    cost++;
                    ptr++;
                }
                if (ptr < n.length && n[ptr] == s2[i]) {
                    ptr++;
                }
                else {
                    cost++;
                }
            }
            cost += n.length - ptr;
            res = Math.min(res, cost);
            p2 = p2 * BigInt(2);
        }
        console.log(res);
    }
}

function main() {
    inputs = inputString.trim().split(/\n| /).map((string) => string.trim());
    inputs.reverse();
    solve();
}

let inputString = '';

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

process.stdin.on('end', (_) => { main(); });

'use strict'
Object.defineProperty(exports, '__esModule', { value: !0 })
var os = require('os')
const stdin = process.stdin,
  stdout = process.stdout,
  integerRegex = /-?\d+/g,
  decimalRegex = /-?\d+(?:\.\d+)?/g
class InputAndOutput {
  lineIndex = 0
  lines = []
  dried() {
    return this.lineIndex >= this.lines.length
  }
  readLine() {
    const e = this.lines[this.lineIndex]
    return (this.lineIndex += 1), e
  }
  readLineAsNumber() {
    return Number(this.readLine())
  }
  readIntegersOfLine() {
    const e = this.readLine().match(integerRegex)
    return null == e ? [] : e.map(e => Number(e))
  }
  readNumsOfLine() {
    const e = this.readLine().match(decimalRegex)
    return null == e ? [] : e.map(e => Number(e))
  }
  print(e) {
    stdout.write(String(e))
  }
  println(e) {
    stdout.write(String(e)), stdout.write('\n')
  }
  async init() {
    const e = await this.readLines()
    this.lines = e
  }
  readLines() {
    const e = []
    return new Promise(n => {
      stdin.on('data', n => e.push(n)),
        stdin.on('end', function () {
          const t = e.join('').split(os.EOL)
          n(t)
        })
    })
  }
}
async function __main__(e) {
  const n = new InputAndOutput()
  await n.init(), e(n)
}
const pow2 = [1n]
for (let e = 1; e < 80; ++e) pow2[e] = 2n * pow2[e - 1]
const pow2s = pow2.map(e => String(e))
function solve(e) {
  let n = 1e4
  const t = String(e)
  for (const e of pow2s) n = Math.min(n, s(t, e))
  return n
  function s(e, n) {
    let t = 0,
      s = 0,
      i = 0
    for (; t < e.length && s < n.length; )
      e[t] !== n[s] ? ((t += 1), (i += 1)) : ((t += 1), (s += 1))
    return (
      t < e.length && (i += e.length - t),
      s < n.length && (i += n.length - s),
      i
    )
  }
}
__main__(function (e) {
  const n = e.readLineAsNumber()
  for (let t = 1; t <= n; ++t) {
    const n = solve(e.readLineAsNumber())
    e.print(n + '\n')
  }
})

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 len = n => n.toString().length;

function sbsq (a, n) {
	a = a.toString();
	n = n.toString();

	let i = 0, j = 0;
	while (i < a.length && j < n.length) {
		if (n[j] == a[i]) i++;
		j++;
	}

	return i == a.length;
}

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

		let ans = len(n) + 1;
		let k = 1n;
		while (k < 1e18) {
			let cur = k;
			while (cur > 0) {
				if (sbsq(cur, n)) {
					ans = Math.min(ans, len(n) - len(cur) + len(k) - len(cur));
				}
				cur /= 10n;
				//cur = BigInt(cur.toString().slice(0,-1));
			}
			k <<= 2n;
		}

		console.log(ans);
	}
}

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 len = n => n.toString().length;

function sbsq (a, n) {
	a = a.toString();
	n = n.toString();

	let i = 0, j = 0;
	while (i < a.length && j < n.length) {
		if (n[j] == a[i]) i++;
		j++;
	}

	return i == a.length;
}

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

		let ans = len(n) + 1;
		let k = 1n;
		while (k < 1e18 && len(k) < 2*len(n)) {
			let cur = k;
			while (cur > 0) {
				if (sbsq(cur, n)) {
					ans = Math.min(ans, len(n) - len(cur) + len(k) - len(cur));
				}
				cur /= 10n;
			}
			k *= 2n;
		}

		console.log(ans);
	}
}

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 len = n => n.toString().length;

function sbsq (a, n) {
	a = a.toString();
	n = n.toString();

	let i = 0, j = 0;
	while (i < a.length && j < n.length) {
		if (n[j] == a[i]) i++;
		j++;
	}

	return i == a.length;
}

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

		let ans = 11;
		let k = 1n;
		while (k < 1e18) {
			let cur = k;
			while (cur > 0) {
				if (sbsq(cur, n)) {
					ans = Math.min(ans, len(n) - len(cur) + len(k) - len(cur));
				}
				cur /= 10n;
			}
			k *= 2n;
		}

		console.log(ans);
	}
}

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 len = n => n.toString().length;

function sbsq (a, n) {
	a = a.toString();
	n = n.toString();

	let i = 0, j = 0;
	while (i < a.length && j < n.length) {
		if (n[j] == a[i]) i++;
		j++;
	}

	return i == a.length;
}

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

		let ans = 11;
		let k = 1;
		while (k < 1e18) {
			let cur = k;
			while (cur > 0) {
				if (sbsq(cur, n)) {
					ans = Math.min(ans, len(n) - len(cur) + len(k) - len(cur));
				}
				cur = Math.floor(cur/10);
			}
			k *= 2;
		}

		console.log(ans);
	}
}

'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++];
}

var maxN = 2 * 1e5 + 10
var mod = BigInt(1e9 + 7)

function main() {
  const xx = readline();
  var array = []
  var res = 1n
  var i =0
  while (i < 200) {
    array.push(res.toString())
    res = res* 2n
    i++
  }
  // console.log(array)
  Array(Number(xx)).fill(1).map((t, i) => {
    var string = readline();
    //
    // var [a, b, c] = readline().split(' ').map((x, iii) => {
    //   return parseInt(x)
    // })
    // console.log(string)
    var min = 10
    for (let j = 0; j < array.length; j++) {

      var same = 0
      var add = 0
      var result = true
      var exist = false
      for (let k = 0; k < array[j].length; k++) {
        exist = false
        for (let i = k + add; i < string.length; i++) {
          if (string[i] === array[j][k]) {
            same++;
            exist = true
            add = i - k
            break
          }
        }
        if (!exist && k === 0) result = false
      }
      if(!result) same = 0
      min = Math.min(Math.abs(string.length - same + (array[j].length - same)), min)
      // console.log(same, array[j], string, min)
    }
    console.log(min)
  })
}

'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++];
}

var maxN = 2 * 1e5 + 10
var mod = BigInt(1e9 + 7)

function main() {
  const xx = readline();
  var array = []
  var res = 1
  while (res <= 10e10) {
    array.push(res.toString())
    res *= 2
  }
  // console.log(array)
  // console.log(array)
  Array(Number(xx)).fill(1).map((t, i) => {
    var string = readline();
    //
    // var [a, b, c] = readline().split(' ').map((x, iii) => {
    //   return parseInt(x)
    // })
    // console.log(string)
    var min = 10
    for (let j = 0; j < array.length; j++) {

      var same = 0
      var add = 0
      var result = true
      var exist = false
      for (let k = 0; k < array[j].length; k++) {
        exist = false
        for (let i = k + add; i < string.length; i++) {
          if (string[i] === array[j][k]) {
            same++;
            exist = true
            add = i - k
            break
          }
        }
        if (!exist && k === 0) result = false
      }
      if(!result) same = 0
      min = Math.min(Math.abs(string.length - same + (array[j].length - same)), min)
      // console.log(same, array[j], string, min)
    }
    console.log(min)
  })
}

"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;
};
let p2 = [];
p2[0] = 1;
p2[1] = 2;
for (let i = 2; i < 40; i++) p2[i] = p2[i - 1] * 2;
for (let i = 0; i < 40; i++) {
  let j = p2[i],
    arr = [];
  while (j > 0) {
    arr.push(j % 10);
    j = Math.floor(j / 10);
  }
  p2[i] = arr.reverse();
}
const solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    let arr = [];
    while (n > 0) {
      arr.push(n % 10);
      n = Math.floor(n / 10);
    }
    arr.reverse();
    const helper = (arr1) => {
      let k = 0,
        op = 0,
        i = 0;
      while (k < arr.length && i < arr1.length) {
        if (arr[k] === arr1[i]) {
          op++;
          i++;
        }
        k++;
      }
      return arr.length - op + (arr1.length - op);
    };
    let ans = Infinity;
    for (let i = 0; i < p2.length; i++) {
      ans = Math.min(ans, helper(p2[i]));
    }
    console.log(ans);
  }
};
solve();


You are given a rooted tree consisting of $$$n$$$ vertices. Vertices are numbered from $$$1$$$ to $$$n$$$. Any vertex can be the root of a tree.A tree is a connected undirected graph without cycles. A rooted tree is a tree with a selected vertex, which is called the root.The tree is specified by an array of parents $$$p$$$ containing $$$n$$$ numbers: $$$p_i$$$ is a parent of the vertex with the index $$$i$$$. The parent of a vertex $$$u$$$ is a vertex that is the next vertex on the shortest path from $$$u$$$ to the root. For example, on the simple path from $$$5$$$ to $$$3$$$ (the root), the next vertex would be $$$1$$$, so the parent of $$$5$$$ is $$$1$$$.The root has no parent, so for it, the value of $$$p_i$$$ is $$$i$$$ (the root is the only vertex for which $$$p_i=i$$$).Find such a set of paths that:  each vertex belongs to exactly one path, each path can contain one or more vertices;  in each path each next vertex — is a son of the current vertex (that is, paths always lead down — from parent to son);  number of paths is minimal. For example, if $$$n=5$$$ and $$$p=[3, 1, 3, 3, 1]$$$, then the tree can be divided into three paths:   $$$3 \rightarrow 1 \rightarrow 5$$$ (path of $$$3$$$ vertices),  $$$4$$$ (path of $$$1$$$ vertices).  $$$2$$$ (path of $$$1$$$ vertices).     Example of splitting a root tree into three paths for $$$n=5$$$, the root of the tree — node $$$3$$$.

The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case consists of two lines. The first of them contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$). It is the number of vertices in the tree. The second line contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$). It is guaranteed that the $$$p$$$ array encodes some rooted tree. It is guaranteed that the sum of the values $$$n$$$ over all test cases in the test does not exceed $$$2 \cdot 10^5$$$.

For each test case on the first line, output an integer $$$m$$$ — the minimum number of non-intersecting leading down paths that can cover all vertices of the tree. Then print $$$m$$$ pairs of lines containing path descriptions. In the first of them print the length of the path, in the second — the sequence of vertices specifying that path in the order from top to bottom. You can output the paths in any order. If there are several answers, output any of them.

'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);
    process.exit(0);
  } 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 P = readline().split(' ').map(a=>a-1);
  //LT({n, P});
  // PROCESSING:
  if (n==1){
    print(1);
    print(1);
    print(1);
    return
  }
  let has_child = {};
  for (let i=0; i<n; i++){
    has_child[P[i]] = true;
  }
  let visited = new Array(n+1).fill(0)
  let ans = [];
  for (let i=0; i<n; i++){
    if (!has_child[i] && !visited[i]){
      let path = [];
      let v = i;
      while (!visited[v]){
        path.push(v+1);
        visited[v] = 1;
        v = P[v];
      }
      ans.push(path);
    }
  }
  let PRINT = ans.length+'\n';
  for (let i=0; i<ans.length; i++){
    let an = ans[i]
    PRINT += an.length+'\n';
    PRINT += an.reverse().join(' ')+'\n'
  }
  console.log(PRINT);
};

'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);
    process.exit(0);
  } 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 P = readline().split(' ').map(a=>a-1);
  //LT({n, P});
  // PROCESSING:
  if (n==1){
    print(1);
    print(1);
    print(1);
    return
  }
  let has_child = {};
  for (let i=0; i<n; i++){
    has_child[P[i]] = true;
  }
  let visited = new Array(n+1).fill(0)
  let ans = [];
  for (let i=0; i<n; i++){
    if (!has_child[i] && !visited[i]){
      let path = [];
      let v = i;
      while (!visited[v]){
        path.push(v+1);
        visited[v] = 1;
        v = P[v];
      }
      ans.push(path);
    }
  }
  let PRINT = ans.length+'\n';
  for (let i=0; i<ans.length; i++){
    let an = ans[i]
    PRINT += an.length+'\n';
    PRINT += an.reverse().join(' ')+'\n'
  }
  process.stdout.write(PRINT+'\n');
};

'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);
    process.exit(0);
  } 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 P = readline().split(' ').map(a=>a-1);
  //LT({n, P});
  // PROCESSING:
  if (n==1){
    print(1);
    print(1);
    print(1);
    return
  }
  let has_child = {};
  for (let i=0; i<n; i++){
    has_child[P[i]] = true;
  }
  let visited = new Array(n+1).fill(0)
  let ans = [];
  for (let i=0; i<n; i++){
    if (!has_child[i] && !visited[i]){
      let path = [];
      let v = i;
      while (!visited[v]){
        path.push(v+1);
        visited[v] = 1;
        v = P[v];
      }
      ans.push(path);
    }
  }
  process.stdout.write(ans.length+'\n');
  for (let i=0; i<ans.length; i++){
    let an = ans[i]
    process.stdout.write(an.length+'\n');
    process.stdout.write(an.reverse().join(' ')+'\n')
    //pa(an.reverse());
  }
  process.stdout.write('\n');
};

"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());
}
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 solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    let arr = iInpArr();
    if (n === 1) {
      console.log(1);
      console.log(1);
      console.log(arr[0]);
      continue;
    }
    let leaf = {};
    for (let i = 0; i < n; i++) leaf[arr[i]] = 1;
    let path = [],
      vis = new Array(n + 1).fill(0);
    for (let i = 1; i <= n; i++) {
      if (leaf[i]) continue;
      let ans = [],
        v = i;
      while (!vis[v]) {
        ans.push(v);
        vis[v] = 1;
        v = arr[v - 1];
      }
      path.push(ans);
    }
  let PRINT = path.length+'\n';
  for (let i=0; i<path.length; i++){
    let an = path[i]
    PRINT += an.length+'\n';
    PRINT += an.reverse().join(' ')+'\n'
  }
  console.log(PRINT);

  }
};
solve();

'use strict';

var readline = require('readline');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, a) {
  const g = Array.from({
    length: n
  }, () => []);
  let root = -1;
  a = a.map(num => num - 1);
  for (let [k, p] of a.entries()) {
    if (k === p) {
      root = p;
    } else {
      g[p].push(k);
    }
  }
  let res = [];
  const queue = [[root, [root]]];
  for (let [u, path] of queue) {
    if (g[u].length === 0) {
      res.push(path.map(num => num + 1));
    } else {
      for (let i = 0; i < g[u].length; i++) {
        const v = g[u][i];
        if (i === 0) {
          path.push(v);
          queue.push([v, path]);
        } else {
          queue.push([v, [v]]);
        }
      }
    }
  }
  let str = [];
  str.push(res.length + '');
  for (let i = 0; i < res.length; i++) {
    str.push(res[i].length + '');
    str.push(res[i].join(' '));
  }
  console.log(str.join('\n'));
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    const n = Number(await read());
    const a = (await read()).split(' ').map(Number);
    solve(n, a);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

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

function div(val, by){
    return (val - val % by) / by;
}

const cnk = (n, k) => {
    let res = 1;
    for (let i = 1; i <= k; i++)
        res = res * (n - k + i) / i;
    return Math.round(res + 0.01);
}

const sumab = (a, b) => {
    let x = (b - a + 1);
    let y = a + b;
    if (x % 2 === 0) {
        x = Math.round(x / 2);
    } else {
        y = Math.round(y / 2);
    }
    return BigInt(x) * BigInt(y);
}

const calc = (n, p)=>{
    let paths = [];
    let hasChildren = new Array(n).fill(false);
    for (let i = 0; i < n; i++) {
        p[i]--;
        if (i === p[i]) continue;
        hasChildren[p[i]] = true;
    }
    let visited = new Array(n).fill(false);
    for (let i = 0; i < n; i++) {
        if (hasChildren[i]) continue;
        let cur = i;
        let path = [];
        while (!visited[cur]) {
            path.push(cur + 1);
            visited[cur] = true;
            cur = p[cur];
        }
        paths.push(path.reverse());
    }

    let result = '';

    result += `${paths.length}\n`;
    for (let i = 0; i < paths.length; i++) {
        result += `${paths[i].length}\n`;
        result += paths[i].join(' ');
        result += '\n';
    }
    result += '\n';
    process.stdout.write(result);
};

function main() {
    let T = +readline();
    for (let t = 1; t <= T; t++){
        let n = +readline();
        // let [n, k] = ra();
        let p = ra();
        // console.log(`${calc(n, p)}`);
        calc(n, p);
    }
}

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 arr = lines[l++].trim().split(' ').map(Number)
        output[i] = solve(n, arr)
    }
    console.log(output.join('\n\n'))
// })()
})

class Queue {
    constructor() {
        this.map = {}
        this.first = 0
        this.last = -1
    }
    push(...args) {
        let i = 0
        if (!this.length) {
            this.first = this.last = 0
            this.map[this.first] = args[i++]
        }
        for (; i < args.length; i++) {
            this.map[++this.last] = args[i]
        }
    }
    unshift(...args) {
        let i = 0
        if (!this.length) {
            this.first = this.last = 0
            this.map[this.first] = args[i++]
        }
        for (; i < args.length; i++) {
            this.map[--this.first] = args[i]
        }
    }
    pop() {
        const r = this.map[this.last]
        delete this.map[this.last]
        this.last--
        return r
    }
    shift() {
        const r = this.map[this.first]
        delete this.map[this.first]
        this.first++
        return r
    }
    get length() {
        if (this.first > this.last) return 0
        return this.last - this.first + 1
    }
}

function solve(n, arr) {
    let r
    const adj = {}
    arr.forEach((p, i) => {
        i++
        if (p === i) {
            r = i
            return
        }
        //
        const a = p
        const b = i
        adj[a] = adj[a] || []
        adj[b] = adj[b] || []
        adj[a].push(b)
        adj[b].push(a)
    })
    const ans = dfs(adj, r, n)
// console.log(ans)
// return
    const map = new Map()
    const output = []
    for (let u = 1; u <= n; u++) {
        const x = ans[u]
        if (map.get(x)) continue
        map.set(x, 1)
        const line = []
        for (let i = x.first; i <= x.last; i++) {
            line.push(x.map[i])
        }
        // output.push(x.length, x.join(' '))
        output.push(x.length, line.join(' '))
    }
    return output.length / 2 + '\n' + output.join('\n')
}
function dfs(adj, r, n) {
    // const stack = [[r, 0, -1]]
    const stack = new Queue()
    stack.push([r, 0, -1])
    const ans = Array(n + 1)
    while (stack.length) {
        const [u, i, p] = stack.map[stack.last]
        // const [u, i, p] = stack[stack.length - 1]
        // visited[u] = 1

        const nb = adj[u] || []
        if (!i) {
            // first visited
        }
        if (i < nb.length) {
            // stack[stack.length - 1][1]++
            stack.map[stack.last][1]++
            const v = nb[i]
            // if (!visited[v]) { // has circle
            if (v !== p) {
                stack.push([v, 0, u])
            }
        } else {
            // last visited
            let max = 0
            let path
            ;(adj[u] || []).forEach(v => {
                if (v === p) return
                if (ans[v].length > max) {
                    max = Math.max(max, ans[v].length)
                    path = ans[v]
                }
            })
            if (path) {
                path.unshift(u)
                ans[u] = path
            } else {
                // ans[u] = [u]
                ans[u] = new Queue()
                ans[u].push(u)
            }
            stack.pop()
        }
    }
    return ans
}

'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 P = ra().map(p=>p-1);
  LT({n, P});
  // PROCESSING:
  if (n==1){
    print(1);
    print(1);
    return
  }
  let G = {};
  for (let i=0; i<n; i++){
    if (!G[P[i]]){
      G[P[i]] = [];
    }
    G[P[i]].push(i);
  }
  let visited = new Set();
  let ans = [];
  for (let i=0; i<n; i++){
    if (!G[i] && !visited.has(i)){
      let path = [];
      let v = i;
      while (!visited.has(v)){
        path.push(v+1);
        visited.add(v);
        v = P[v];
      }
      ans.push(path);
    }
  }
  print(ans.length);
  for (let an of ans){
    print(an.length);
    pa(an.reverse());
  }
  //print();
};

'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 P = ra().map(p=>p-1);
  LT({n, P});
  // PROCESSING:
  let root;
  let G = {};
  for (let i=0; i<n; i++){
    if (i==P[i])
      root = i;
    if (!G[P[i]]){
      G[P[i]] = [];
    }
    G[P[i]].push(i);
  }
  let visited = new Set();
  let ans = [];
  for (let i=0; i<n; i++){
    if (!G[i] && !visited.has(i)){
      let path = [];
      let v = i;
      while (!visited.has(v)){
        path.push(v+1);
        visited.add(v);
        v = P[v];
      }
      ans.push(path);
    }
  }
  print(ans.length);
  for (let an of ans){
    print(an.length);
    pa(an.reverse());

  }
  //print();
};

'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 P = ra().map(p=>p-1);
  LT({n, P});
  // PROCESSING:
  let root;
  let G = {};
  for (let i=0; i<n; i++){
    if (i==P[i])
      root = i;
    if (!G[P[i]]){
      G[P[i]] = [];
    }
    G[P[i]].push(i);
  }
  let visited = new Set();
  let ans = [];
  for (let i=0; i<n; i++){
    if (!G[i] && !visited.has(i)){
      let path = [];
      let v = i;
      while (!visited.has(v)){
        path.push(v+1);
        visited.add(v);
        v = P[v];
      }
      ans.push(path);
    }
  }
  print(ans.length);
  for (let an of ans){
    print(an.length);
    pa(an.reverse());

  }
  print();
};

'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 P = ra().map(p=>p-1);
  LT({n, P});
  // PROCESSING:
  let root;
  let G = {};
  for (let i=0; i<n; i++){
    if (i==P[i])
      root = i;
    if (!G[P[i]]){
      G[P[i]] = [];
    }
    G[P[i]].push(i);
  }
  let visited = new Set();
  let ans = [];
  for (let i=0; i<n; i++){
    if (!G[i] && !visited.has(i)){
      let path = [];
      let v = i;
      while (!visited.has(v)){
        path.push(v+1);
        visited.add(v);
        v = P[v];
      }
      ans.push(path);
    }
  }
  print(ans.length);
  for (let an of ans){
    print(an.length);
    pa(an);

  }
  //print();
};

'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 P = ra().map(p=>p-1);
  LT({n, P});
  // PROCESSING:
  let root;
  let G = {};
  for (let i=0; i<n; i++){
    if (i==P[i])
      root = i;
    if (!G[P[i]]){
      G[P[i]] = [];
    }
    G[P[i]].push(i);
  }
  let visited = new Set();
  let ans = [];
  for (let i=0; i<n; i++){
    if (!G[i] && !visited.has(i)){
      let path = [];
      let v = i;
      while (!visited.has(v)){
        path.push(v+1);
        visited.add(v);
        v = P[v];
      }
      ans.push(path);
    }
  }
  print(ans.length);
  for (let an of ans){
    print(an.length);
     pa(an);

  }
  print();
};

"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());
}
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));
};
class graph {
  constructor() {
    this.list = {};
  }
  add(v) {
    if (!this.list[v]) this.list[v] = [];
  }
  addE(v, e) {
    if (this.list[v]) this.list[v].push(e);
  }
}
const solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    let arr = iInpArr();
    if (n === 1) {
      console.log(1);
      console.log(1);
      console.log(arr[0]);
      continue;
    }
    let g = new graph();
    for (let i = 0, j = 1; i < n; i++, j++) {
      g.add(arr[i]);
      if (arr[i] !== j) g.addE(arr[i], j);
    }
    let path = [],
      res = [];
    const dfs = (g) => {
      let visted = {};
      const helper = (v) => {
        path.push(v);
        if (g.list[v] === undefined) {
          let narr = [];
          for (let i = 0; i < path.length; i++) {
            if (visted[path[i]] === undefined) {
              narr.push(path[i]);
              visted[path[i]] = 1;
            }
          }
          res.push(narr);
          return;
        }
        let arr = g.list[v];
        for (let i = 0; i < arr.length; i++) {
          helper(arr[i]);
          path.pop();
        }
      };
      helper(arr[0]);
    };
    dfs(g);
    console.log(res.length);
    for (let i = 0; i < res.length; i++) {
      console.log(res[i].length);
      console.log(res[i].join(" "));
    }
  }
};
solve();

'use strict';

var readline = require('readline');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, a) {
  const g = Array.from({
    length: n + 1
  }, () => []);
  let root = -1;
  for (let [k, p] of a.entries()) {
    if (k + 1 === p) {
      root = p;
    } else {
      g[p].push(k + 1);
    }
  }
  let res = [];
  const dfs = (i, path = []) => {
    path.push(i);
    if (g[i].length === 0) {
      res.push(path);
      return;
    }
    for (let j = 0; j < g[i].length; j++) {
      if (j === 0) {
        dfs(g[i][j], path);
      } else {
        dfs(g[i][j]);
      }
    }
  };
  dfs(root);
  let str = [];
  str.push(res.length + '');
  for (let i = 0; i < res.length; i++) {
    str.push(res[i].length + '');
    str.push(res[i].join(' '));
  }
  console.log(str.join('\n'));
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    const n = Number(await read());
    const a = (await read()).split(' ').map(Number);
    solve(n, a);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

'use strict';

var readline = require('readline');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, a) {
  const g = Array.from({
    length: n
  }, () => []);
  let root = -1;
  for (let [k, p] of a.entries()) {
    p--;
    if (k === p) {
      root = p;
    } else {
      g[p].push(k);
    }
  }
  let res = [];
  const dfs = (i, path = []) => {
    path.push(i);
    if (g[i].length === 0) {
      res.push(path.map(num => num + 1));
      return;
    }
    for (let j = 0; j < g[i].length; j++) {
      if (j === 0) {
        dfs(g[i][j], path);
      } else {
        dfs(g[i][j]);
      }
    }
  };
  dfs(root);
  let str = [];
  str.push(res.length + '');
  for (let i = 0; i < res.length; i++) {
    str.push(res[i].length + '');
    str.push(res[i].join(' '));
  }
  console.log(str.join('\n'));
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    const n = Number(await read());
    const a = (await read()).split(' ').map(Number);
    solve(n, a);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

'use strict';

var readline = require('readline');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, a) {
  const g = Array.from({
    length: n
  }, () => []);
  let root = -1;
  for (let [k, p] of a.entries()) {
    p--;
    if (k === p) {
      root = p;
    } else {
      g[p].push(k);
    }
  }
  let res = [];
  const dfs = (i, path = []) => {
    path.push(i);
    if (g[i].length === 0) {
      res.push(path.map(num => num + 1));
      return;
    }
    for (let j = 0; j < g[i].length; j++) {
      if (j === 0) {
        dfs(g[i][j], path);
      } else {
        dfs(g[i][j]);
      }
    }
  };
  dfs(root);
  let str = res.length + '\n';
  for (let i = 0; i < res.length; i++) {
    str += res[i].length + '\n';
    str += res[i].join(' ') + '\n';
  }
  console.log(str);
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    const n = Number(await read());
    const a = (await read()).split(' ').map(Number);
    solve(n, a);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

'use strict';

var readline = require('readline');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, a) {
  const g = Array.from({
    length: n
  }, () => []);
  let root = -1;
  for (let [k, p] of a.entries()) {
    p--;
    if (k === p) {
      root = p;
    } else {
      g[p].push(k);
    }
  }
  let res = [];
  const dfs = (i, path = []) => {
    path.push(i);
    if (g[i].length === 0) {
      res.push(path.map(num => num + 1));
      return;
    }
    for (let j = 0; j < g[i].length; j++) {
      if (j === 0) {
        dfs(g[i][j], path);
      } else {
        dfs(g[i][j]);
      }
    }
  };
  dfs(root);
  let str = res.length + '\n';
  console.log(res.length);
  for (let i = 0; i < res.length; i++) {
    str += res[i].length + '\n';
    str += res[i].join(' ') + '\n';
  }
  console.log(str);
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    const n = Number(await read());
    const a = (await read()).split(' ').map(Number);
    solve(n, a);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();


You are given a sequence of positive integers a1, a2, ..., an. Find all such indices i, that the i-th element equals the arithmetic mean of all other elements (that is all elements except for this one).

The first line contains the integer n (2 ≤ n ≤ 2·105). The second line contains elements of the sequence a1, a2, ..., an (1 ≤ ai ≤ 1000). All the elements are positive integers.

Print on the first line the number of the sought indices. Print on the second line the sought indices in the increasing order. All indices are integers from 1 to n. If the sought elements do not exist, then the first output line should contain number 0. In this case you may either not print the second line or print an empty line.

var getVals = function () { return readline().split(' '); };

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

//134A
var n = parseInt(readline());
var nums = getNums();
var sum = nums.reduce((a, b) => a + b);
var res = [];
for(var i = 0; i < n; i++) {
    if (nums[i] === (sum - nums[i])/(n-1)) {
        res.push(i+1);
    }
}
print(res.length);
print(res.join(' '));

var getVals = function () { return readline().split(' '); };

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

//134A
var n = parseInt(readline());
var nums = getNums();
var sum = nums.reduce((a, b) => a + b);
var res = [];
for(var i = 0; i < n; i++) {
    if (nums[i] === (sum - nums[i])/(n-1)) {
        res.push(nums[i]);
    }
}
print(res.length);
print(res.join(' '));


oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array:   Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$.  Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the arrays $$$a$$$ and $$$b$$$, where $$$b$$$ is a permutation of $$$a$$$, determine if $$$b$$$ has the maximum sadness over all permutations of $$$a$$$.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$)  — the elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_i \leq n$$$)  — the elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print "AC" (without quotes) if $$$b$$$ has the maximum sadness over all permutations of $$$a$$$, and "WA" (without quotes) otherwise.

NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.In the third test case, the array $$$[2,1]$$$ has sadness $$$0$$$.In the fourth test case, the array $$$[3,2,3,1]$$$ has sadness $$$1$$$.

'use strict';

var readline = require('readline');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, a, b) {
  a = a.map(num => num - 1);
  b = b.map(num => num - 1);
  const g = Array.from({
    length: n
  }, () => []);
  const map = new Map();
  for (let i = 0; i < n; i++) {
    var _map$get;
    map.set(a[i], ((_map$get = map.get(a[i])) !== null && _map$get !== void 0 ? _map$get : 0) + 1);
  }
  const t = [...map.entries()].sort((a, b) => b[1] - a[1])[0];
  const d = new Array(n).fill(-1),
        set = new Set();
  for (let i = 0; i < n; i++) {
    const u = b[i],
          v = a[i];
    if (u === t[0]) continue;
    if (d[u] === -1) d[u] = 0;
    if (d[v] === -1) d[v] = 0;
    set.add(u);
    set.add(v);
    d[v]++;
    g[u].push(v);
  }
  const queue = [];
  for (let [k, v] of d.entries()) if (v === 0) queue.push(k);
  const st = [];
  for (let u of queue) {
    st[u] = 1;
    for (let v of g[u]) {
      if (st[v]) {
        console.log('WA');
        return;
      }
      d[v]--;
      if (d[v] === 0) queue.push(v);
    }
  }
  if (queue.length === set.size) console.log('AC');else console.log('WA');
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    const n = Number(await read());
    const a = (await read()).split(' ').map(Number);
    const b = (await read()).split(' ').map(Number);
    solve(n, a, b);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

'use strict';

var readline = require('readline');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, a, b) {
  if (n === 1) {
    console.log('AC');
    return;
  }
  a = a.map(num => num - 1);
  b = b.map(num => num - 1);
  const g = Array.from({
    length: n
  }, () => []);
  const map = new Map();
  for (let i = 0; i < n; i++) {
    var _map$get;
    map.set(a[i], ((_map$get = map.get(a[i])) !== null && _map$get !== void 0 ? _map$get : 0) + 1);
  }
  const t = [...map.entries()].sort((a, b) => b[1] - a[1])[0];
  const d = new Array(n).fill(-1);
  for (let i = 0; i < n; i++) {
    const u = b[i],
          v = a[i];
    if (u === t[0]) continue;
    if (d[u] === -1) d[u] = 0;
    if (d[v] === -1) d[v] = 0;
    d[v]++;
    g[u].push(v);
  }
  const queue = [];
  for (let [k, v] of d.entries()) if (v === 0) queue.push(k);
  const st = [];
  for (let u of queue) {
    st[u] = 1;
    for (let v of g[u]) {
      if (st[v]) {
        console.log('WA');
        return;
      }
      d[v]--;
      if (d[v] === 0) queue.push(v);
    }
  }
  if (queue.length === n - (t[1] - 1)) console.log('AC');else console.log('WA');
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    const n = Number(await read());
    const a = (await read()).split(' ').map(Number);
    const b = (await read()).split(' ').map(Number);
    solve(n, a, b);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

'use strict';

var readline = require('readline');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, a, b) {
  a = a.map(num => num - 1);
  b = b.map(num => num - 1);
  const g = Array.from({
    length: n
  }, () => []);
  const map = new Map();
  for (let i = 0; i < n; i++) {
    var _map$get;
    map.set(a[i], ((_map$get = map.get(a[i])) !== null && _map$get !== void 0 ? _map$get : 0) + 1);
  }
  const t = [...map.entries()].sort((a, b) => b[1] - a[1])[0];
  const d = new Array(n).fill(-1);
  for (let i = 0; i < n; i++) {
    const u = b[i],
          v = a[i];
    if (u === t[0]) continue;
    if (d[u] === -1) d[u] = 0;
    if (d[v] === -1) d[v] = 0;
    d[v]++;
    g[u].push(v);
  }
  const queue = [];
  for (let [k, v] of d.entries()) if (v === 0) queue.push(k);
  const st = [];
  for (let u of queue) {
    st[u] = 1;
    for (let v of g[u]) {
      if (st[v]) {
        console.log('WA');
        return;
      }
      d[v]--;
      if (d[v] === 0) queue.push(v);
    }
  }
  if (queue.length === n - t[1] + 1) console.log('AC');else console.log('WA');
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    const n = Number(await read());
    const a = (await read()).split(' ').map(Number);
    const b = (await read()).split(' ').map(Number);
    solve(n, a, b);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

'use strict';

var readline = require('readline');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, a, b) {
  a = a.map(num => num - 1);
  b = b.map(num => num - 1);
  const g = Array.from({
    length: n
  }, () => []);
  const map = new Map();
  for (let i = 0; i < n; i++) {
    var _map$get;
    map.set(a[i], ((_map$get = map.get(a[i])) !== null && _map$get !== void 0 ? _map$get : 0) + 1);
  }
  const t = [...map.entries()].sort((a, b) => b[1] - a[1])[0][0];
  for (let i = 0; i < n; i++) {
    if (b[i] === t || a[i] === t) continue;
    g[b[i]].push(a[i]);
  }
  let visit = new Set(),
      visit1 = new Set();
  const check = u => {
    if (visit1.has(u)) return false;
    visit1.add(u);
    let res = true;
    for (let v of g[u]) {
      if (g[v].length === 0 || visit.has(v)) continue;
      res = res && check(v);
    }
    return res;
  };
  for (let [u, edges] of g.entries()) {
    if (!edges.length || visit.has(u)) continue;
    visit1 = new Set();
    if (!check(u)) {
      console.log('WA');
      return;
    }
    for (let num of visit1) {
      visit.add(num);
    }
  }
  console.log('AC');
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    const n = Number(await read());
    const a = (await read()).split(' ').map(Number);
    const b = (await read()).split(' ').map(Number);
    solve(n, a, b);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

'use strict';

var readline = require('readline');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, a, b) {
  a = a.map(num => num - 1);
  b = b.map(num => num - 1);
  const g = Array.from({
    length: n
  }, () => []);
  const map = new Map();
  for (let i = 0; i < n; i++) {
    var _map$get;
    map.set(a[i], ((_map$get = map.get(a[i])) !== null && _map$get !== void 0 ? _map$get : 0) + 1);
  }
  const t = [...map.entries()].sort((a, b) => b[1] - a[1])[0][0];
  for (let i = 0; i < n; i++) {
    if (b[i] === t) continue;
    g[b[i]].push(a[i]);
  }
  let visit = new Set(),
      visit1 = new Set();
  const check = u => {
    if (visit1.has(u)) return false;
    visit1.add(u);
    let res = true;
    for (let v of g[u]) {
      if (g[v].length === 0 || visit.has(v)) continue;
      res = res && check(v);
    }
    return res;
  };
  for (let [u, edges] of g.entries()) {
    if (!edges.length || visit.has(u)) continue;
    visit1 = new Set();
    if (!check(u)) {
      console.log('WA');
      return;
    }
    for (let num of visit1) {
      visit.add(num);
    }
  }
  console.log('AC');
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    const n = Number(await read());
    const a = (await read()).split(' ').map(Number);
    const b = (await read()).split(' ').map(Number);
    solve(n, a, b);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

'use strict';

var readline = require('readline');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, a, b) {
  a = a.map(num => num - 1);
  b = b.map(num => num - 1);
  const g = Array.from({
    length: n
  }, () => []);
  const map = new Map();
  for (let i = 0; i < n; i++) {
    var _map$get;
    map.set(a[i], ((_map$get = map.get(a[i])) !== null && _map$get !== void 0 ? _map$get : 0) + 1);
  }
  const t = [...map.entries()].sort((a, b) => b[1] - a[1])[0][0];
  for (let i = 0; i < n; i++) {
    if (b[i] === t) continue;
    g[b[i]].push(a[i]);
  }
  const st = new Set();
  const check = u => {
    st.add(u);
    let res = true;
    for (let v of g[u]) {
      if (g[v].length === 0) continue;
      if (st.has(v)) return false;
      res = res && check(v);
    }
    return res;
  };
  for (let [u, edges] of g.entries()) {
    if (!edges.length || st.has(u)) continue;
    if (!check(u)) {
      console.log('WA');
      return;
    }
  }
  console.log('AC');
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    const n = Number(await read());
    const a = (await read()).split(' ').map(Number);
    const b = (await read()).split(' ').map(Number);
    solve(n, a, b);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();