You are given a rectangular grid with $$$n$$$ rows and $$$m$$$ columns. The cell located on the $$$i$$$-th row from the top and the $$$j$$$-th column from the left has a value $$$a_{ij}$$$ written in it.You can perform the following operation any number of times (possibly zero):  Choose any two adjacent cells and multiply the values in them by $$$-1$$$. Two cells are called adjacent if they share a side. Note that you can use a cell more than once in different operations.You are interested in $$$X$$$, the sum of all the numbers in the grid. What is the maximum $$$X$$$ you can achieve with these operations?

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$,$$$m$$$ ($$$2 \le n$$$, $$$m \le 10$$$).  The following $$$n$$$ lines contain $$$m$$$ integers each, the $$$j$$$-th element in the $$$i$$$-th line is $$$a_{ij}$$$ ($$$-100\leq a_{ij}\le 100$$$).

For each testcase, print one integer $$$X$$$, the maximum possible sum of all the values in the grid after applying the operation as many times as you want.

NoteIn the first test case, there will always be at least one $$$-1$$$, so the answer is $$$2$$$. In the second test case, we can use the operation six times to elements adjacent horizontally and get all numbers to be non-negative. So the answer is: $$$2\times 1 + 3\times2 + 3\times 3 + 2\times 4 + 1\times 5 = 30$$$.

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

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

function main() {
  let t = +readLine();
  while (t--) {
    const [rowLen, colLen] = readLine().split(" ").map(Number);
    let [sum, min, countMinus] = [0, Infinity, 0];
    for (let row = 0; row < rowLen; row++) {
      readLine()
        .split(" ")
        .map((n) => {
          n = parseInt(n);
          if (n < 0) countMinus++;
          sum += Math.abs(n);
          min = Math.min(min, Math.abs(n));
          return n;
        });
    }
    if (countMinus % 2 === 1) sum -= 2 * min;

    console.log(sum);
  }
}

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

let inputString = '';
let currentLine = 0;

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

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

    B();
});

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

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

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

    return a;
}

function gcd(x, y) {
    if ((typeof x !== 'number') || (typeof y !== 'number'))
      return false;
    x = Math.abs(x);
    y = Math.abs(y);
    while(y) {
      var t = y;
      y = x % y;
      x = t;
    }
    return x;
  }

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

        for(let i = 0; i < n; i++){
            for(let j = 1; j < m; j++){
                if(mat[i][j] < 0 && mat[i][j-1] < 0){
                    mat[i][j] = -1*mat[i][j];
                    mat[i][j-1] = -1*mat[i][j-1];
                }
            }
        }

        for(let i = 0; i < m; i++){
            for(let j = 1; j < n; j++){
                if(mat[j][i] < 0 && mat[j-1][i] < 0){
                    mat[j][i] *= -1;
                    mat[j-1][i] *= -1;
                }
            }
        }

        let count = 0;
        let min = 99999999999;
        let sum = 0;
        for(let i = 0; i < n; i++){
            for(let j = 0; j < m; j++){
                if(mat[i][j] < 0){
                    count += 1;
                }

                min = Math.min(min, Math.abs(mat[i][j]));
                sum += Math.abs(mat[i][j]);
            }
        }

        if(count % 2 === 0){
            console.log(sum);
        }else{
            console.log(sum-2*min);
        }
    }
}

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

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

function main() {
  let t = +readLine();
  while (t--) {
    const [rowLen, colLen] = readLine().split(" ").map(Number);
    let [sum, min, foundMinus] = [0, Infinity, false];
    for (let row = 0; row < rowLen; row++) {
      readLine()
        .split(" ")
        .map((n) => {
          n = parseInt(n);
          if (!foundMinus && n < 0) foundMinus = true;
          sum += Math.abs(n);
          min = Math.min(min, Math.abs(n));
          return n;
        });
    }
    if (foundMinus) sum -= 2 * min;

    console.log(sum);
  }
}


You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$.    An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$.    An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.

In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.

NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow):  first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices;  the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion;  then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it;  the vertex $$$4$$$ will be connected with the vertex $$$3$$$;  then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth);  you will just delete the vertex $$$4$$$;  there are no more vertices to delete.   In the second example you don't need to delete any vertex:  vertices $$$2$$$ and $$$3$$$ have children that respect them;  vertices $$$4$$$ and $$$5$$$ respect ancestors.   In the third example the tree will change this way:

const readline = require('readline');

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

function readLines(number, cb) {
    const lines = [];
    rl.on('line', function(line) {
        lines.push(line);
        if (lines.length === number) {
            rl.close();
            cb(lines);
        }
    });
};

function readLines(cb) {
    const lines = [];
    let read;

    rl.on('line', function(line) {
        if (!read) {
            read = parseInt(line);
        } else {
            lines.push(line);
        }
        if (lines.length === read) {
            rl.close();
            cb(lines);
        }
    });
};
readLines(doIt);

function doIt(lines) {
    const tree = [];
    lines.forEach(item => {
        tree.push(item.split(" ").map(x => parseInt(x)));
    });
    tree.forEach(item => {
        let p = item[0];
        let c = item[1];
        if (c === 0 && p!==-1 && tree[p-1][1] ===1) {
            tree[p-1].push(0);
        }
    });
    const out = [];
    tree.forEach((item, idx)=>{
        if (item.length==2 && item[1] === 1)
            out.push(idx+1);
    })
    if (out.length === 0)
        console.log(-1);
    else
        console.log(out.join(' '));
}

const readline = require('readline');

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

function readLines(number, cb) {
    const lines = [];
    rl.on('line', function(line) {
        lines.push(line);
        if (lines.length === number) {
            rl.close();
            cb(lines);
        }
    });
};

function readLines(cb) {
    const lines = [];
    let read;

    rl.on('line', function(line) {
        if (!read) {
            read = parseInt(line);
        } else {
            lines.push(line);
        }
        if (lines.length === read) {
            rl.close();
            cb(lines);
        }
    });
};
readLines(doIt);

function doIt(lines) {
    const tree = [];
    lines.forEach(item => {
        tree.push(item.split(" ").map(x => parseInt(x)));
    });
    tree.forEach(item => {
        let p = item[0];
        let c = item[1];
        if (c === 0 && p!==-1 && tree[p-1][1] ===1) {
            tree[p-1][1] = 0;
        }
    });
    const out = [];
    tree.forEach((item, idx)=>{
        if (item[1] === 1)
            out.push(idx+1);
    })
    if (out.length === 0)
        console.log(-1);
    else
        console.log(out.join(' '));
}

const readline = require('readline');

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

function readLines(number, cb) {
    const lines = [];
    rl.on('line', function(line) {
        lines.push(line);
        if (lines.length === number) {
            rl.close();
            cb(lines);
        }
    });
};

function readLines(cb) {
    const lines = [];
    let read;

    rl.on('line', function(line) {
        if (!read) {
            read = parseInt(line);
        } else {
            lines.push(line);
        }
        if (lines.length === read) {
            rl.close();
            cb(lines);
        }
    });
};
readLines(doIt);

function doIt(lines) {
    const tree = [];
    lines.forEach(item => {
        tree.push(item.split(" ").map(x => parseInt(x)));
    });
    console.log(lines)
    tree.forEach(item => {
        let p = item[0];
        let c = item[1];
        if (c === 0 && p!==-1 && tree[p-1][1] ===1) {
            tree[p-1][1] = 0;
        }
    });
    const out = [];
    tree.forEach((item, idx)=>{
        if (item[1] === 1)
            out.push(idx+1);
    })
    if (out.length === 0)
        console.log(-1);
    else
        console.log(out.join(' '));
}


The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other — the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added).

The first line of the input contains a single number n (1 ≤ n ≤ 105) — the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≤ hi ≤ 109), where hi equals the number of floors in the i-th house.

Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one.

readline();

var line = readline();

var heights = line.split(" ");

var n = heights.length;

var maxRight = new Array(n);

maxRight[n - 1] = 0;

var neededFloors =  [];

for (var i = n - 2; i >= 0; i--) {
    maxRight[i] = Math.max(maxRight[i + 1], heights[i + 1]);
}

for (var i = 0; i < n; i++) {
    var difference = maxRight[i] - heights[i];
    neededFloors.push(heights[i] > maxRight[i]? 0 : difference + 1);
}

print(neededFloors.join(" "));

var n = readline();
var houses = readline().split(" ");

var max = -1, L = houses.length, result = new Array(n);
for (var i = L-1; i>=0; --i) {
  var T = houses[i];
  result[i] = T > max ? 0 : max - T + 1;
  max = Math.max(T, max);
}

print(result.join(" "));

readline();
var houses = readline().split(" ");

var max = -1, L = houses.length, result = [];
for (var i = L-1; i>=0; --i) {
  var T = houses[i];
  result.push(T > max ? 0 : max - T + 1);
  max = Math.max(T, max);
}

result.reverse();
print(result.join(" "));

var n = parseInt(readline());
var houses = readline().split(' ').map(function(c){ return parseInt(c); });
var indexmax = n - 1;
var extrafloors = [];

for(var i = n - 1; i >= 0; i--)
{

	if(houses[i] > houses[indexmax])
	{
		indexmax = i;
		extrafloors.unshift(0);
	}
	else if(houses[i] == houses[indexmax])
	{
		if(i == indexmax)
			extrafloors.unshift(0);
		else
			extrafloors.unshift(1);
	}
	else
		extrafloors.unshift(houses[indexmax] - houses[i] + 1);
}

print(extrafloors.join(" "));

var numeric = readline(),
		floor = readline().split(' '),
		result = [0];

for (; floor.length > 1; ) {
	var last_floor = +floor[floor.length - 1],
			prev_floor = +floor[floor.length - 2];

	if (prev_floor > last_floor) {
		result.unshift(0);
		floor.splice(floor.length - 1, 1);
	} else {
		if (last_floor === prev_floor) {
			result.unshift(1);
			floor.splice(floor.length - 1, 1);
		} else {
			result.unshift( (last_floor - prev_floor) + 1 );
		floor.splice(floor.length - 2, 1);
		}
	}
}

//result.splice(0,1);
print(result.join(' '));

var numeric = readline(),
		floor = readline().split(' '),
		result = [0];

for (; floor.length; ) {
	var last_floor = +floor[floor.length - 1],
			prev_floor = +floor[floor.length - 2];

	if (prev_floor > last_floor) {
		result.unshift(0);
		floor.pop();
	} else {
		if (last_floor === prev_floor) {
			result.unshift(1);
			floor.pop();
		} else {
			result.unshift( (last_floor - prev_floor) + 1 );
		floor.splice(floor.length - 2, 1);
		}
	}
}

result.splice(0,1);
print(result.join(' '));

var numeric = readline(),
		floor = readline().split(' '),
		result = [0];

for (; floor.length; ) {
	var last_floor = +floor[floor.length - 1],
			prev_floor = +floor[floor.length - 2];

	if (prev_floor > last_floor) {
		result.unshift(0);
		floor.splice(floor.length - 1, 1);
	} else {
		if (last_floor === prev_floor) {
			result.unshift(1);
			floor.splice(floor.length - 1, 1);
		} else {
			result.unshift( (last_floor - prev_floor) + 1 );
		floor.splice(floor.length - 2, 1);
		}
	}
}

result.splice(0,1);
print(result.join(' '));

/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};

/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {

/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;

/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};

/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;

/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}

/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;

/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;

/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";

/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {

	var Prelude_1 = __webpack_require__(1);
	var List = __webpack_require__(2);
	var n = parseInt(readline());
	var xs = List.map(parseInt, readline().split(' '));
	var result = [];
	var highest = 0;
	for (var i = xs.length - 1; i >= 0; i--) {
	    result.push(Prelude_1.max(highest + 1, xs[i]) - xs[i]);
	    highest = Prelude_1.max(highest, xs[i]);
	}
	result = List.reverse(result);
	print(result.join(" "));

/***/ },
/* 1 */
/***/ function(module, exports) {

	function min(a, b) {
	    return a < b ? a : b;
	}
	exports.min = min;
	function max(a, b) {
	    return a < b ? b : a;
	}
	exports.max = max;
	function curry(f) {
	    return function (x) { return function (y) { return f(x, y); }; };
	}
	exports.curry = curry;
	function uncurry(f) {
	    return function (x, y) { return f(x)(y); };
	}
	exports.uncurry = uncurry;
	function id(x) {
	    return x;
	}
	exports.id = id;
	function constant(x) {
	    return function (_) { return x; };
	}
	exports.constant = constant;
	function flip(f) {
	    return function (y) { return function (x) { return f(x)(y); }; };
	}
	exports.flip = flip;
	function flip2(f) {
	    return function (y, x) { return f(x, y); };
	}
	exports.flip2 = flip2;
	function compose(g, f) {
	    return function (x) { return g(f(x)); };
	}
	exports.compose = compose;

/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {

	var Prelude_1 = __webpack_require__(1);
	function add(xs, ys) {
	    return xs.concat(ys);
	}
	exports.add = add;
	function head(xs) {
	    return xs[0];
	}
	exports.head = head;
	function last(xs) {
	    return xs[xs.length - 1];
	}
	exports.last = last;
	function tail(xs) {
	    return xs.slice(1);
	}
	exports.tail = tail;
	function init(xs) {
	    return xs.slice(0, xs.length - 1);
	}
	exports.init = init;
	function map(f, xs) {
	    var result = new Array(xs.length);
	    for (var i = 0; i < xs.length; i++) {
	        result[i] = f(xs[i]);
	    }
	    return result;
	}
	exports.map = map;
	function reverse(xs) {
	    return xs.slice().reverse();
	}
	exports.reverse = reverse;
	function intersperse(x, xs) {
	    if (xs.length == 0) {
	        return [];
	    }
	    var result = new Array(xs.length + xs.length - 1);
	    for (var i = 0; i + 1 < xs.length; i++) {
	        result[i + i] = xs[i];
	        result[i + i + 1] = x;
	    }
	    result[result.length - 1] = xs[xs.length - 1];
	    return result;
	}
	exports.intersperse = intersperse;
	function intercalate(xs, xss) {
	    return concat(intersperse(xs, xss));
	}
	exports.intercalate = intercalate;
	function foldl(f, initial, xs) {
	    var result = initial;
	    for (var i = 0; i < xs.length; i++) {
	        result = f(result, xs[i]);
	    }
	    return result;
	}
	exports.foldl = foldl;
	function foldr(f, initial, xs) {
	    var result = initial;
	    for (var i = xs.length - 1; i >= 0; i--) {
	        result = f(xs[i], result);
	    }
	    return result;
	}
	exports.foldr = foldr;
	function concat(xss) {
	    var total = sum(map(function (xs) { return xs.length; }, xss));
	    var result = new Array(total);
	    var m = 0;
	    for (var i = 0; i < xss.length; i++) {
	        var xs = xss[i];
	        for (var j = 0; j < xs.length; j++) {
	            result[m++] = xs[j];
	        }
	    }
	    return result;
	}
	exports.concat = concat;
	function sum(xs) {
	    var result = 0;
	    for (var i = 0; i < xs.length; i++) {
	        result += xs[i];
	    }
	    return result;
	}
	exports.sum = sum;
	function product(xs) {
	    var result = 1;
	    for (var i = 0; i < xs.length; i++) {
	        result *= xs[i];
	    }
	    return result;
	}
	exports.product = product;
	function maximum(xs) {
	    var result = xs[0];
	    for (var i = 1; i < xs.length; i++) {
	        if (result < xs[i])
	            result = xs[i];
	    }
	    return result;
	}
	exports.maximum = maximum;
	function minimum(xs) {
	    var result = xs[0];
	    for (var i = 1; i < xs.length; i++) {
	        if (result > xs[i])
	            result = xs[i];
	    }
	    return result;
	}
	exports.minimum = minimum;
	function replicate(n, x) {
	    var result = new Array(n);
	    for (var i = 0; i < result.length; i++) {
	        result[i] = x;
	    }
	    return result;
	}
	exports.replicate = replicate;
	function take(n, xs) {
	    return xs.slice(0, n);
	}
	exports.take = take;
	function drop(n, xs) {
	    return xs.slice(n);
	}
	exports.drop = drop;
	function splitAt(n, xs) {
	    return [take(n, xs), drop(n, xs)];
	}
	exports.splitAt = splitAt;
	function takeWhile(f, xs) {
	    for (var i = 0; i < xs.length; i++) {
	        if (!f(xs[i])) {
	            return xs.slice(0, i);
	        }
	    }
	    return xs.slice();
	}
	exports.takeWhile = takeWhile;
	function dropWhile(f, xs) {
	    for (var i = 0; i < xs.length; i++) {
	        if (!f(xs[i])) {
	            return xs.slice(i);
	        }
	    }
	    return [];
	}
	exports.dropWhile = dropWhile;
	function group(xs) {
	    if (xs.length == 0) {
	        return [];
	    }
	    var result = [];
	    var last = [xs[0]];
	    for (var i = 1; i < xs.length; i++) {
	        if (last[0] === xs[i]) {
	            last.push(xs[i]);
	        }
	        else {
	            result.push(last);
	            last = [xs[i]];
	        }
	    }
	    result.push(last);
	    return result;
	}
	exports.group = group;
	function filter(f, xs) {
	    var result = [];
	    for (var i = 0; i < xs.length; i++) {
	        if (f(xs[i]))
	            result.push(xs[i]);
	    }
	    return result;
	}
	exports.filter = filter;
	function zip(xs, ys) {
	    var n = Prelude_1.min(xs.length, ys.length);
	    var result = new Array(n);
	    for (var i = 0; i < n; i++) {
	        result[i] = [xs[i], ys[i]];
	    }
	    return result;
	}
	exports.zip = zip;
	function unzip(xs) {
	    var r1 = new Array(xs.length);
	    var r2 = new Array(xs.length);
	    for (var i = 0; i < xs.length; i++) {
	        r1[i] = xs[i][0];
	        r2[i] = xs[i][1];
	    }
	    return [r1, r2];
	}
	exports.unzip = unzip;

/***/ }
/******/ ]);

var n = readline();
var h = readline().split(" ");
var res = [];
var flag;
// for(var i = 0; i < n; i++){
// 	var max = parseInt(h[i]);
// 	for(var j = i+1; j < n; j++){
// 		flag = (parseInt(h[j]) == max) ? 1 : 0;
// 		max = (parseInt(h[j]) > max) ? parseInt(h[j]) : max;
// 	}
// 	var r = (max == parseInt(h[i])) ? (flag) ? 1 : 0 : (max - parseInt(h[i]) + 1);
// 	res.push(r);
// }
// print(res.join(' '));
res = [];
var max = -1;
for(var i = n-1; i >= 0; i--){
	if(parseInt(h[i]) > max){
		max = parseInt(h[i]);
		flag = 1;
	}
	else
		flag = 0;
	var r =  (flag) ?  0 : (max - parseInt(h[i]) + 1);
	res.push(r);
}
print(res.reverse().join(' '));

var n = parseInt(readline());
var input = readline().split(' ').map(function (item) {
	return parseInt(item);
})
var result = [];
input.reduceRight(function (prev, curr) {
	if(curr > prev){
		result.push(0);
	} else if (curr === prev) {
		result.push(1);
	} else {
		result.push(prev - curr + 1);
	}
	return Math.max(prev, curr);
}, 0)
result = result.reverse();
print(result.join(' '));

readline();

var line = readline();

var heights = line.split(" ");

var n = heights.length;

var maxRight = new Array(n);

maxRight[n - 1] = 0;

var neededFloors =  [];

for (var i = n - 2; i >= 0; i--) {
    maxRight[i] = Math.max(maxRight[i + 1], heights[i + 1]);
}

for (var i = 0; i < n; i++) {
    var difference = maxRight[i] - heights[i];
    neededFloors.push(heights[i] > maxRight[i]? 0 : difference);
}

print(neededFloors.join(" "));

readline();

var line = readline();

var heights = line.split(" ");

var n = heights.length;

var maxRight = new Array(n);

maxRight[n - 1] = 0;

var neededFloors =  [];

for (var i = n - 2; i >= 0; i--) {
    maxRight[i] = Math.max(maxRight[i - 1], heights[i - 1]);
}

for (var i = 0; i < n; i++) {
    var difference = maxRight[i] - heights[i];
    neededFloors.push(heights[i] > maxRight[i]? 0 : difference);
}

print(neededFloors.join(" "));

readline();

var line = readline();

var heights = line.split(" ");

var n = heights.length;

var maxRight = new Array(n);

maxRight[n - 1] = 0;

var neededFloors =  [];

for (var i = n - 2; i >= 0; i--) {
    maxRight[i] = Math.max(maxRight[i - 1], heights[i - 1]);
}

for (var i = n - 1; i >= 0; i--) {
    var difference = maxRight[i] - heights[i];
    neededFloors.push(heights[i] < maxRight[i]? difference : 0);
}

print(neededFloors.join(" "));

var n = parseInt(readline());
var houses = readline().split(' ').map(function(c){ return parseInt(c); });
var indexmax = 0;
var extrafloors = [];

for(var i = n; i >= 1; i--)
{
	if(houses[i] > houses[indexmax])
		extrafloors.unshift(houses[indexmax] + 1 - houses[i]);
	else
	{
		extrafloors.unshift(0);
		indexmax = i;
	}
}

print(extrafloors.join(" "));

var n = parseInt(readline());
var houses = readline().split(' ').map(function(c){ return parseInt(c); });
var indexmax = n - 1;
var extrafloors = [];

for(var i = n - 1; i >= 0; i--)
{
	if(houses[i] >= houses[indexmax])
	{
		extrafloors.unshift(0);
		indexmax = i;
	}
	else
		extrafloors.unshift(houses[indexmax] - houses[i] + 1);
}

print(extrafloors.join(" "));

var n = parseInt(readline());
var houses = readline().split(' ').map(function(c){ return parseInt(c); });
var indexmax = 0;
var extrafloors = [];

for(var i = n - 1; i >= 1; i--)
{
	if(houses[i] > houses[indexmax])
		extrafloors.unshift(houses[indexmax] + 1 - houses[i]);
	else
	{
		extrafloors.unshift(0);
		indexmax = i;
	}
}

print(extrafloors.join(" "));

var n = parseInt(readline());
var houses = readline().split(' ').map(function(c){ return parseInt(c); });
var max = 0;
var extrafloors = [];

for(var i = n - 1; i >= 0; i--)
{
	if(houses[i] < max)
		extrafloors.unshift(max - houses[i] + 1);
	else
	{
		extrafloors.unshift(0);
		max = houses[i];
	}
}

print(extrafloors.join(" "));

var n = parseInt(readline());
var houses = readline().split(' ').map(function(c){ return parseInt(c); });
var indexmax = n - 1;
var extrafloors = [];

for(var i = n - 1; i >= 0; i--)
{
	if(houses[i] > houses[indexmax])
		extrafloors.unshift(houses[indexmax] + 1 - houses[i]);
	else
	{
		extrafloors.unshift(0);
		indexmax = i;
	}
}

print(extrafloors.join(" "));

var n = parseInt(readline());
var houses = readline().split(' ').map(function(c){ return parseInt(c); });
var indexmax = n - 1;
var extrafloors = [];

for(var i = n - 1; i >= 0; i--)
{
	if(houses[i] < houses[indexmax])
		extrafloors.unshift(houses[indexmax] + 1 - houses[i]);
	else
	{
		extrafloors.unshift(0);
		indexmax = i;
	}
}

print(extrafloors.join(" "));

var n = parseInt(readline());
var houses = readline().split(' ').map(function(c){ return parseInt(c); });
var indexmax = n - 1;
var extrafloors = [];

for(var i = n - 1; i >= 0; i--)
{
	if(houses[i] < houses[indexmax])
		extrafloors.unshift(houses[indexmax] - houses[i] + 1);
	else
	{
		extrafloors.unshift(0);
		indexmax = i;
	}
}

print(extrafloors.join(" "));

var n = parseInt(readline());
var houses = readline().split(' ').map(function(c){ return parseInt(c); });
var indexmax = n - 1;
var extrafloors = [];

for(var i = n - 1; i >= 0; i--)
{
	if(houses[i] > houses[indexmax])
	{
		extrafloors.unshift(0);
		indexmax = i;
	}
	else
		extrafloors.unshift(houses[indexmax] - houses[i] + 1);
}

print(extrafloors.join(" "));

var numeric = readline(),
		floor = readline().split(' '),
		result = [0];

for (; floor.length; ) {
	var last_floor = +floor[floor.length - 1],
			prev_floor = +floor[floor.length - 2];

	if (prev_floor > last_floor) {
		result.unshift(0);
		floor.splice(floor.length - 1, 1);
	} else {
		if (last_floor === prev_floor) {
			result.unshift(0);
			floor.splice(floor.length - 1, 1);
		} else {
			result.unshift( (last_floor - prev_floor) + 1 );
		floor.splice(floor.length - 2, 1);
		}
	}
}
result.splice(0,1);
print(result.join(' '));

var numeric = readline(),
		floor = readline().split(' '),
		result = [0];

for (; floor.length; ) {
	var last_floor = +floor[floor.length - 1],
			prev_floor = floor[floor.length - 2];

	if (prev_floor > last_floor) {
		result.unshift(0);
		floor.splice(floor.length - 1, 1);
	} else {
		if (last_floor == prev_floor) {
			result.unshift(0);
			floor.splice(floor.length - 1, 1);
		} else {
			result.unshift(last_floor + 1 - prev_floor);
		floor.splice(floor.length - 2, 1);
		}
	}
}
result.splice(0,1);
print(result.join(' '));

var numeric = readline(),
		floor = readline().split(' '),
		result = [0];

for (; floor.length > 0; ) {
	var last_floor = +floor[floor.length - 1],
			prev_floor = +floor[floor.length - 2];

	if (prev_floor > last_floor) {
		result.unshift(0);
		floor.splice(floor.length - 1, 1);
	} else {
		if (last_floor === prev_floor) {
			result.unshift(1);
			floor.splice(floor.length - 1, 1);
		} else {
			result.unshift( (last_floor - prev_floor) + 1 );
		floor.splice(floor.length - 2, 1);
		}
	}
}

//result.splice(0,1);
print(result.join(' '));

var n = parseInt(readline());
var input = readline().split(' ').map(function (item) {
	return parseInt(item);
})
var max = input.reduce(function (prev, curr) {
	return Math.max(prev, curr);
}, 0)
print(input.map(function (item) {
	return (item === max) ? 0 : max - item + 1;
}).join(' '));

var n = parseInt(readline());
var input = readline().split(' ').map(function (item) {
	return parseInt(item);
})
var result = [];
input.reduceRight(function (prev, curr) {
	var max = Math.max(prev, curr);
	if(curr === max){
		result.push(0);
	} else {
		result.push(max - curr + 1);
	}
	return max;
}, 0)
result = result.reverse();
print(result.join(' '));


A map of some object is a rectangular field consisting of n rows and n columns. Each cell is initially occupied by the sea but you can cover some some cells of the map with sand so that exactly k islands appear on the map. We will call a set of sand cells to be island if it is possible to get from each of them to each of them by moving only through sand cells and by moving from a cell only to a side-adjacent cell. The cells are called to be side-adjacent if they share a vertical or horizontal side. It is easy to see that islands do not share cells (otherwise they together form a bigger island).Find a way to cover some cells with sand so that exactly k islands appear on the n × n map, or determine that no such way exists.

The single line contains two positive integers n, k (1 ≤ n ≤ 100, 0 ≤ k ≤ n2) — the size of the map and the number of islands you should form.

If the answer doesn't exist, print "NO" (without the quotes) in a single line. Otherwise, print "YES" in the first line. In the next n lines print the description of the map. Each of the lines of the description must consist only of characters 'S' and 'L', where 'S' is a cell that is occupied by the sea and 'L' is the cell covered with sand. The length of each line of the description must equal n. If there are multiple answers, you may print any of them. You should not maximize the sizes of islands.

function toi(x){return parseInt(x);}
var s=readline().split(" ").map(toi);
var n=s[0];
var k=s[1];
var num=0;
var res="";
for(var i=0;i<n;i++){
    for(var j=0;j<n;j++){
	if((i+j)%2==0&&num<k){
	   res+= "L";
	   num++;
	}else{
	   res+="S";
	}
    }
    if(i!=n-1)res+="\n";
}
print(num==k?"YES\n"+res:"NO");

data = readline().split(' ').map(Number);
n = data[0];
k = data[1];
if (k > Math.floor(n*n)/2+n%2) {
	print('NO');
}
else {
	print('YES');
	for (i = 0 ; i<n ; i++){
		msg = '';
		for (j = 0; j<n;j++){
			if (k!=0 && i%2==j%2){
				msg +='L';
				k--;
			}
			else {
				msg +='S';
			}
		}
		print(msg);
	}
}

var line = readline().split(' ');
var N = parseInt(line[0]), K = parseInt(line[1]);
var total = (N * N + 1);
total = (total - (total % 2)) / 2;
if( K > total )
    print("NO");
else {
    print("YES");
    var i, j, k = 0;
    for(i = 0; i < N; i ++) {
        for(j = 0; j < N; j ++) {
            if( (i + j) % 2 == 0 && k < K ) {
                write('L');
                k ++;
            } else write('S');
        }
        print("");
    }
}

var n = parseInt( readline() ),
	k = parseInt( readline() );

if (k > (n+1)/2) {
	print( 'NO' );
} else {
	var cur = 0;
	for (var i=0; i<n; i++) {
		var s = '';
		for (var j=0; j<n; j++) {
			s 	+= cur < k && (i + j)%2 ? 'L' : 'S';
			cur += cur < k && (i + j)%2 ? 1 : 0;
		}
		print( s );
	}
}

data = readline().split(' ').map(Number);
n = data[0];
k = data[1];
if (k > Math.floor(n/2)+n%2){
	print('NO');
}
else {
	print('Yes');
	prevLand = false;
	for (i = 0 ; i<n ; i++){
		msg = '';
		for (j = 0; j<n;j++){
			if (!prevLand && k!=0){
				msg +='L';

			}
			else {
				msg +='S';
			}
		}
		print(msg);
		if (!prevLand) {
			if (k!= 0){
				k--;
			}
		}
		prevLand = !prevLand;

	}
}

data = readline().split(' ').map(Number);
n = data[0];
k = data[1];
if (k > Math.floor(n/2)+n%2){
	print('NO');
}
else {
	print('YES');
	prevLand = false;
	for (i = 0 ; i<n ; i++){
		msg = '';
		for (j = 0; j<n;j++){
			if (!prevLand && k!=0){
				msg +='L';

			}
			else {
				msg +='S';
			}
		}
		print(msg);
		if (!prevLand) {
			if (k!= 0){
				k--;
			}
		}
		prevLand = !prevLand;

	}
}

data = readline().split(' ').map(Number);
n = data[0];
k = data[1];
if (k > Math.floor(n*n)/2+k%2) {
	print('NO');
}
else {
	print('YES');
	for (i = 0 ; i<n ; i++){
		msg = '';
		for (j = 0; j<n;j++){
			if (k!=0 && i%2==j%2){
				msg +='L';
				k--;
			}
			else {
				msg +='S';
			}
		}
		print(msg);
	}
}


Daisy loves playing games with words. Recently, she has been playing the following Deletive Editing word game with Daniel. Daisy picks a word, for example, "DETERMINED". On each game turn, Daniel calls out a letter, for example, 'E', and Daisy removes the first occurrence of this letter from the word, getting "DTERMINED". On the next turn, Daniel calls out a letter again, for example, 'D', and Daisy removes its first occurrence, getting "TERMINED". They continue with 'I', getting "TERMNED", with 'N', getting "TERMED", and with 'D', getting "TERME". Now, if Daniel calls out the letter 'E', Daisy gets "TRME", but there is no way she can get the word "TERM" if they start playing with the word "DETERMINED".Daisy is curious if she can get the final word of her choice, starting from the given initial word, by playing this game for zero or more turns. Your task it help her to figure this out.

The first line of the input contains an integer $$$n$$$ — the number of test cases ($$$1 \le n \le 10\,000$$$). The following $$$n$$$ lines contain test cases.  Each test case consists of two words $$$s$$$ and $$$t$$$ separated by a space. Each word consists of at least one and at most 30 uppercase English letters; $$$s$$$ is the Daisy's initial word for the game; $$$t$$$ is the final word that Daisy would like to get at the end of the game.

Output $$$n$$$ lines to the output — a single line for each test case. Output "YES" if it is possible for Daisy to get from the initial word $$$s$$$ to the final word $$$t$$$ by playing the Deletive Editing game. Output "NO" otherwise.

6

DETERMINED TRME

DETERMINED TERM

PSEUDOPSEUDOHYPOPARATHYROIDISM PEPA

DEINSTITUTIONALIZATION DONATION

CONTEST CODE

SOLUTION SOLUTION

"use strict";
process.stdin.resume();
process.stdin.setEncoding("utf-8");

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

let inputString = "";
let currentLine = 0;

process.stdin.on("data", inputStdin => {
    inputString += inputStdin;
});
process.stdin.on("end", () => {
    inputString = inputString.split("\n");
    main();
});
function readline() {
    return inputString[currentLine++];
}
// ********** Code Start **********

function main() {
    // your code goes here

var t = parseInt(readline());

while (t--) {

    let mp = new Map();
    let mp1 = new Map();

    let [ch, ch1] = readline().trim().split(" ");

    for (let i = 0; i < ch.length; i++) {
        if (mp.has(ch[i]))
            mp.set(ch[i], mp.get(ch[i]) + 1);
        else
            mp.set(ch[i], 1);
    }

    for (let i = 0; i < ch1.length; i++) {
        if (mp1.has(ch1[i]))
            mp1.set(ch1[i], mp1.get(ch1[i]) + 1);
        else
            mp1.set(ch1[i], 1);
    }

    let s = "";

    for (let i = 0; i < ch.length; i++) {
        if (mp.get(ch[i]) <= mp1.get(ch[i]))
            s += ch[i];
        else
            mp.set(ch[i], mp.get(ch[i]) - 1);
    }

    //console.log("map size ", mp.size);

    if (s === ch1)
        console.log("YES");
    else
        console.log("NO");
}

}

"use strict";
process.stdin.resume();
process.stdin.setEncoding("utf-8");

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

let inputString = "";
let currentLine = 0;

process.stdin.on("data", inputStdin => {
    inputString += inputStdin;
});
process.stdin.on("end", () => {
    inputString = inputString.split("\n");
    main();
});
function readline() {
    return inputString[currentLine++];
}
// ********** Code Start **********

function main() {
    // your code goes here

var t = parseInt(readline());

while (t--) {

    let mp = new Map();
    let mp1 = new Map();

    let [ch, ch1] = readline().trim().split(" ");

    for (let i = 0; i < ch.length; i++) {
        if (mp.has(ch[i]))
            mp.set(ch[i], mp.get(ch[i]) + 1);
        else
            mp.set(ch[i], 1);
    }

    for (let i = 0; i < ch1.length; i++) {
        if (mp1.has(ch1[i]))
            mp1.set(ch1[i], mp1.get(ch1[i]) + 1);
        else
            mp1.set(ch1[i], 1);
    }

    let s = "";

    for (let i = 0; i < ch.length; i++) {
        if (mp.get(ch[i]) <= mp1.get(ch[i]))
            s += ch[i];
        else
            mp.set(ch[i], mp.get(ch[i]) - 1);
    }

    //console.log("map size ", mp.size);

    if (s === ch1)
        console.log("YES");
    else
        console.log("NO");
}}

const readline = require('readline')

let inputs = []
let lineNum = 0

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

rl.on('line', input => {
  inputs.push(input)
})

rl.on('close', () => {
  let n = readLine()
  n = Number(n)
  for(let i=0; i<n; i++){
    let input = readLine()
    let [s, t] = input.split(' ')
    solution(s, t)
  }
})

function readLine(){
  return inputs[lineNum++]
}

function solution(s, t){
  let arr = Array.from({ length: s.length }).map(_ => 0)
  let idx = s.length-1
  for(let i=t.length-1; i>=0; i--){
    let char = t[i]
    let flag = false
    for(let j=idx; j>=0; j--){
      if(arr[j] !== 0) continue
      if(s[j] !== char){
        for(let k=j; k>=0; k--){
          if(s[k] === s[j]){
            arr[k] = -1
          }
        }
      }else{
        flag = true
        arr[j] = 1
        idx = j-1
        break
      }
    }
    if(!flag){
      console.log('NO')
      return
    }
  }
  console.log('YES')
}

'use strict';

var fs = require('fs');

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

var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);

function solve(s, t) {
  const map = new Map();

  for (let i = 0; i < t.length - 1; i++) {
    var _map$get;

    const c = t[i];
    map.set(c, ((_map$get = map.get(c)) !== null && _map$get !== void 0 ? _map$get : 0) + 1);
  }

  for (let i = s.length - 1, j = t.length - 1; i >= 0; i--) {
    if (s[i] === t[j]) {
      j--;
      map.set(t[j], map.get(t[j]) - 1);
    } else {
      if (map.get(s[i])) return false;
    }

    if (j === -1) return true;
  }

  return false;
}

// const inputs = fs.readFileSync(path.join(__dirname, './codeforces.test.txt'), 'utf-8').split('\n')

const inputs = fs__default["default"].readFileSync(0, 'utf-8').split('\n');
void function main() {
  const _ = Number(inputs[0]);

  for (let __ = 1; __ <= _; __++) {
    const [s, t] = inputs[__].trim().split(' ');

    console.log(solve(s, t) ? 'YES' : 'NO');
  }
}();

"use strict";
process.stdin.resume();
process.stdin.setEncoding("utf-8");

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

let inputString = "";
let currentLine = 0;

process.stdin.on("data", inputStdin => {
    inputString += inputStdin;
});
process.stdin.on("end", () => {
    inputString = inputString.split("\n");
    main();
});
function readline() {
    return inputString[currentLine++];
}
// ********** Code Start **********

function main() {
    // your code goes here

    let t = parseInt(readline());

    while (t--) {

        let mp = new Map();
        let mp1 = new Map();

        let [ch, ch1] = readline();

        for (let i = 0; i < ch.length; i++) {
            if (mp.has(ch[i]))
                mp.set(ch[i], mp.get(ch[i]) + 1);
            else
                mp.set(ch[i], 1);
        }

        for (let i = 0; i < ch1.length; i++) {
            if (mp1.has(ch1[i]))
                mp1.set(ch1[i], mp1.get(ch1[i]) + 1);
            else
                mp1.set(ch1[i], 1);
        }

        let s = "";

        for (let i = 0; i < ch.length; i++) {
            if (mp.get(ch[i]) <= mp1.get(ch[i]))
                s += ch[i];
            else
                mp.set(ch[i], mp.get(ch[i]) - 1);
        }

        //console.log("map size ", mp.size);

        if (s == ch1)
            console.log("YES");
        else
            console.log("NO");
    }

}


Polycarp has built his own web service. Being a modern web service it includes login feature. And that always implies password security problems.Polycarp decided to store the hash of the password, generated by the following algorithm:  take the password $$$p$$$, consisting of lowercase Latin letters, and shuffle the letters randomly in it to obtain $$$p'$$$ ($$$p'$$$ can still be equal to $$$p$$$);  generate two random strings, consisting of lowercase Latin letters, $$$s_1$$$ and $$$s_2$$$ (any of these strings can be empty);  the resulting hash $$$h = s_1 + p' + s_2$$$, where addition is string concatenation. For example, let the password $$$p =$$$ "abacaba". Then $$$p'$$$ can be equal to "aabcaab". Random strings $$$s1 =$$$ "zyx" and $$$s2 =$$$ "kjh". Then $$$h =$$$ "zyxaabcaabkjh".Note that no letters could be deleted or added to $$$p$$$ to obtain $$$p'$$$, only the order could be changed.Now Polycarp asks you to help him to implement the password check module. Given the password $$$p$$$ and the hash $$$h$$$, check that $$$h$$$ can be the hash for the password $$$p$$$.Your program should answer $$$t$$$ independent test cases.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains a non-empty string $$$p$$$, consisting of lowercase Latin letters. The length of $$$p$$$ does not exceed $$$100$$$. The second line of each test case contains a non-empty string $$$h$$$, consisting of lowercase Latin letters. The length of $$$h$$$ does not exceed $$$100$$$.

For each test case print the answer to it — "YES" if the given hash $$$h$$$ could be obtained from the given password $$$p$$$ or "NO" otherwise.

5
abacaba
zyxaabcaabkjh
onetwothree
threetwoone
one
zzonneyy
one
none
twenty
ten

NoteThe first test case is explained in the statement.In the second test case both $$$s_1$$$ and $$$s_2$$$ are empty and $$$p'=$$$ "threetwoone" is $$$p$$$ shuffled.In the third test case the hash could not be obtained from the password.In the fourth test case $$$s_1=$$$ "n", $$$s_2$$$ is empty and $$$p'=$$$ "one" is $$$p$$$ shuffled (even thought it stayed the same). In the fifth test case the hash could not be obtained from the password.

'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 readALine() {
    return inputString[currentLine++];
}

function printALine(str) {
    console.log(str);
}

function stringArrayToNumbers(str) {
    var array = str.split(" ");
    var result = [];
    for( var i = 0; i < array.length; i++ ) {
        result.push( parseInt(array[i]) );
    }
    return result;
}

function stringArrayToBigInts(str) {
    var array = str.split(" ");
    var result = [];
    for( var i = 0; i < array.length; i++ ) {
        result.push( BigInt(array[i]) );
    }
    return result;
}

// ======================================================
// A. Shuffle Hashing
// https://codeforces.com/problemset/problem/1278/A
// ======================================================

// Convert p to array. Sort the array then convert it back to a string.
function _process(str) {
    var arr = str.split('');
    arr.sort();
    return arr.join('');
}

function doIt( p, h ) {

    //printALine("P=" + p + " H=" + h);
    var processedP = _process(p);
    //printALine("  Processed P=" + processedP);

    for( var i = 0; i < h.length; i++ ) {
        var str = h.substring(i, i + p.length);
        var processedStr = _process(str);
        //printALine("  Substring=" + str + " Processed=" + processedStr);
        if( processedStr == processedP ) {
            return "YES";
        }
    }

    return "NO";

}

function main() {

    var numOfTests = parseInt(readALine());
    for( var i = 0; i < numOfTests; i++ ) {
        var string1 = readALine();
        var string2 = readALine();
        var result = doIt( string1, string2 );
        printALine(result);
    }

}

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++) {
    // wr(j)
    let p = arr[2 * j]
    const h = arr[2 * j + 1]

    const pa = p.split('')
    const ha = h.split('')

    const pl = p.length, hl = h.length
    p = pa.sort().join('')
    let flag = false

    for(let i = 0; i < hl - pl + 1; i++) {
      let t = h.substr(i, pl)
      t = t.split('').sort().join('')
      if(t == p) {
        flag = true
        break
      }
    }
    flag ? wr('YES') : wr('NO')
  }
})

function wr(...x) {
  console.log(...x)
}

function max(...x) {
  return Math.max(...x)
}

function min(...x) {
  return Math.min(...x)
}

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

let index = 0;
let p = '', h = '';

readline.on('line', line => {
  if (index++) {
    if (!p) {
      p = line;
      return;
    } else {
      h = line;
      let tmp = p, flag = false;
      for(let i = 0, j = 0; i < h.length; ) {
        let ind = tmp.indexOf(h[i]);
        if (ind != -1) {
          tmp = tmp.slice(0, ind) + tmp.slice(ind + 1);
          if (!tmp.length) flag = true;
          i++;
        } else {
          tmp = p;
          j++;
          i = j;
        }
      }
      if (flag) console.log("YES");
      else console.log("NO");
    }
    p = '';
  }
});

// readline.on("close", () => {
//   console.log(count, values);
// });

var print = this.print || require('lol-io').print; //print --> outputs result and adds (enter)
var write = this.write || require('lol-io').write; //write --> creates output.txt with output
var readline = this.readline || require('lol-io').readline; //readline --> reads unread line of input.txt

var t, p, h, sorted, answer, substring;

t = Number(readline());

function check (array1, array2) {

    if ((array1.length == array2.length) && array1.every(function(element, index) {
    return element === array2[index]})) {return true} else {return false}
}

for (i = 0; i < t; i++) {                   //Loop each test

    p = readline().replace(/\r$/, '');
    h = readline().replace(/\r$/, '');
    answer = "NO";
    sorted = p.split('').sort();

    for (k = 0; k < h.length - p.length + 1; k++) {        //

        for (j = 0; j < h.length; j++) {
            substring = h.substr(j, p.length).split('').sort();

            if (check(substring, sorted)) {
                answer = "YES";
                break;
            }
        }
    }

    print(answer);
}

var t = parseInt(readline(), 10),
    p = [],
    h = [];

for(var i=1; i<=t; i++) {
    p = readline().split('').sort();
    h = readline().split('');

    var demo_p = [], demo_p_sort = [];

    for(var j=0; j<h.length; j++) {
        demo_p.push(h[j]);

        if(j>=p.length-1) {
            demo_p_sort = [...demo_p].sort();

            if(demo_p_sort.join('') === p.join('')) {
                print('YES');
                break;
            } else if(j === h.length - 1) print('NO');
            else demo_p.shift();

        } else if(j === h.length - 1) print('NO');
    }
}

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 n = parseInt(arr[0])

  const a = arr[1].split(' ').map(a => parseInt(a))

  let ans = 1
  if(n == 1) {
    console.log(1)
    return
  }
  for(let i = 1; i < n; i++) {
    if(n >= 2 && a[i] >= a[i - 1] && (i + 1) % 2 == 0) ans = max(ans, 2)
    if(i >= 3 && n >= 4 && a[i] >= a[i - 1] && a[i - 1] >= a[i - 2] && a[i - 2] >= a[i - 3] && (i + 1) % 4 == 0) ans = max(ans, 4)
    if(i >= 7 && n >= 8 && a[i] >= a[i - 1] && a[i - 1] >= a[i - 2] && a[i - 2] >= a[i - 3] && a[i - 3] >= a[i - 4] && a[i - 4] >= a[i - 5] && a[i - 5] >= a[i - 6] && a[i - 6] >= a[i - 7] && (i + 1) % 8 == 0) ans = max(ans, 8)
    let flag = true
    if(i == 15) {
      for(let j = 1; j < n; j++) {
        if(a[j] < a[j - 1]) {
          flag = false
          break
        }
      }
    }
    if(flag && i == 15) {
      ans = 16
    }
  }
  wr(ans)
})

function wr(...x) {
  console.log(...x)
}

function max(...x) {
  return Math.max(...x)
}

function min(...x) {
  return Math.min(...x)
}


Valera had two bags of potatoes, the first of these bags contains x (x ≥ 1) potatoes, and the second — y (y ≥ 1) potatoes. Valera — very scattered boy, so the first bag of potatoes (it contains x potatoes) Valera lost. Valera remembers that the total amount of potatoes (x + y) in the two bags, firstly, was not gerater than n, and, secondly, was divisible by k.Help Valera to determine how many potatoes could be in the first bag. Print all such possible numbers in ascending order.

The first line of input contains three integers y, k, n (1 ≤ y, k, n ≤ 109;   ≤ 105).

Print the list of whitespace-separated integers — all possible values of x in ascending order. You should print each possible value of x exactly once. If there are no such values of x print a single integer -1.

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

function solve(){
    let y, k, n;
    let line = readLine().split(' ').map(Number);
    y = line[0], k = line[1], n = line[2];
    let arr = [];

    for(let i = k; i <= n; i += k){
        if(i-y > 0) arr.push(i-y);
    }
    if(arr.length)
        for(let i of arr)
            process.stdout.write(`${i} `);
    else
        console.log(-1);
}

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

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

function main() {
  const [y, k, n] = readLine().split(" ").map(Number);
  const result = [];
  for (let i = 1; i * k <= n; i++) {
    const num = k * i;
    if (num > y) {
      result.push(num - y);
    }
  }
  if (result.length) console.log(result.join(" "));
  else console.log(-1);
}

print(function(y, k, n) {
	var i,ans = [];
	for (i = k; i <= n; i += k)
		ans.push(i);

	ans = ans.map(function(v) {
		return v - y;
	}).filter(function(v) {
		return v >= 1;
	});

	if (ans.length === 0) return -1;
	return ans.join(' ');

} .apply(0, readline().split(' ').map(Number)));

print(function(y, k, n) {
	var i,
		ans = [];

	for (i = k * Math.ceil(y / k) - y, l = n - y; i <= l; i += k)
		if (i >= 1) ans.push(i);

	if (ans.length === 0) return -1;
	return ans.join(' ');

} .apply(0, readline().split(' ').map(Number)));

print(function(y, k, n) {

	var ans = [];
	for (var i = k, l = Math.min(1e9,n); i <= l; i+=k)
		ans.push(i);

	ans = ans.map(function(v) {
		return v - y;
	}).filter(function(v) {
		return v >= 1;
	});

	if(ans.length===0) return -1;
	return ans.join(' ');

} .apply(0, readline().split(' ').map(Number)));

;(function () {

	print(function (y, k, n) {
		var r = [], l = 0;

		while (++l * k <= n)
			if (l*k > y)
				r.push( l*k - y);

		if (!r.length) return -1;
		else return r.join(' ');
	}.apply(0, readline().split(' ').map(Number)));

}).call(this);

function trim(s) {
	return s.replace(/^\s+|\s+$/gm, '');
}

function tokenize(s) {
	return trim(s).split(/\s+/);
}

function tokenizeIntegers(s) {
	var tokens = tokenize(s);
	for (var i = 0; i < tokens.length; i += 1) {
		tokens[i] = parseInt(tokens[i], 10);
	};
	return tokens;
}

function main() {
	var data = tokenizeIntegers(readline()),
		y = data[0], k = data[1], n = data[2],
		result = [];
	for (var sum = Math.ceil((y+1)/k)*k; sum <= n; sum += k) {
		result.push(sum-y);
	}
	if (result.length == 0) {
		print(-1);
	} else {
		print(result.join(' '));
	}
}

main();

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

function solve(){
    let y, k, n;
    let line = readLine().split(' ').map(Number);
    y = line[0], k = line[1], n = line[2];
    let arr = [];

    for(let i = k*2; i <= n; i += k){
        if(i-y > 0) arr.push(i-y);
    }
    if(arr.length)
        for(let i of arr)
            process.stdout.write(`${i} `);
    else
        console.log(-1);
}

print(function(y, k, n) {

	var ans = [];
	for (var i = 1, l = Math.min(1e5,n); i <= l; i++)
		if (i % k === 0) ans.push(i);

	ans = ans.map(function(v) {
		return v - y;
	}).filter(function(v) {
		return v >= 1;
	});

	if(ans.length===0) return -1;
	return ans.join(' ');

} .apply(0, readline().split(' ').map(Number)));

print(function(y, k, n) {
	var i,
		ans = [];

	if (y === k) return -1;
	for (i = k * Math.ceil(y / k) - y, l = n - y; i <= l; i += k)
		ans.push(i);

	if (ans.length === 0) return -1;
	return ans.join(' ');

} .apply(0, readline().split(' ').map(Number)));

print(function(y, k, n) {
	var i,
		ans = [];

	for (i = k * Math.ceil(y / k) - y, l = n - y; i <= l; i += k)
		ans.push(i);

	if (ans.length === 0) return -1;
	return ans.join(' ');

} .apply(0, readline().split(' ').map(Number)));


You have an image file of size $$$2 \times 2$$$, consisting of $$$4$$$ pixels. Each pixel can have one of $$$26$$$ different colors, denoted by lowercase Latin letters.You want to recolor some of the pixels of the image so that all $$$4$$$ pixels have the same color. In one move, you can choose no more than two pixels of the same color and paint them into some other color (if you choose two pixels, both should be painted into the same color).What is the minimum number of moves you have to make in order to fulfill your goal?

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Each test case consists of two lines. Each of these lines contains two lowercase letters of Latin alphabet without any separators, denoting a row of pixels in the image.

For each test case, print one integer — the minimum number of moves you have to make so that all $$$4$$$ pixels of the image have the same color.

5

rb

br

cc

wb

aa

aa

ab

cd

yy

xx

NoteLet's analyze the test cases of the example.In the first test case, you can paint the bottom left pixel and the top right pixel (which share the same color) into the color r, so all pixels have this color.In the second test case, two moves are enough:  paint both top pixels, which have the same color c, into the color b;  paint the bottom left pixel into the color b. In the third test case, all pixels already have the same color.In the fourth test case, you may leave any of the pixels unchanged, and paint all three other pixels into the color of that pixel in three moves.In the fifth test case, you can paint both top pixels into the color x.

const t = Number(readline());

for (i = 0; i < t; i++) {
  currentImage = readline() + readline();

  uniqueColors = new Set(currentImage.split(''));
  nrOfUniqueColors = [...uniqueColors].length;

  print(nrOfUniqueColors - 1);
}

var t = Number(readline())

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

    var line1 = readline()
    var line2 = readline()
    var pixels = line1 + line2

    var tmp = {}

    for (var j = 0; j < pixels.length; j++) {
        if (tmp[pixels[j]] === undefined)
            tmp[pixels[j]] = true
    }

    print(Object.keys(tmp).length - 1)
}

var t = Number(readline())

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

    var line1 = readline()
    var line2 = readline()
    var pixels = line1.split("").concat(line2.split(""))

    var tmp = {}

    for (var j = 0; j < pixels.length; j++) {
        if (tmp[pixels[j]] === undefined)
            tmp[pixels[j]] = 1
        else
            tmp[pixels[j]]++
    }

    print(String(Object.keys(tmp).length - 1))
}

function solveForOneInput(fullLine){
  const allLetters = ['a','b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
  var usedLetters = 0
  for (var i=0; i<26; i++){
    var currentLetter = allLetters[i]
    if (fullLine.includes(currentLetter)){
        usedLetters = usedLetters+1
    }
  }
  print(usedLetters-1)
}

const n = readline()
for (var i=0;i<n;i++){
  var line1=readline()
  var line2=readline()
  var fullLine = line1+line2
  solveForOneInput(fullLine)
}

var repeatTimes = readline();

while (repeatTimes--) {
    var str1 = readline()
    var str2 = readline()
    var set1 = new Set()
    set1.add(str1[0])
    set1.add(str1[1])
    set1.add(str2[0])
    set1.add(str2[1])
    print(set1.size - 1)
}

tests = parseInt(readline())

function getMoves(){
	image = (readline() + readline()).split("").sort()
	// 1: all pixels are the same
	if(image[0] == image[3]) return 0;
	// 2: AAAB
	if(image[0] == image[2]) return 1;
	if(image[1] == image[3]) return 1;

	// 3: AABB
	if(image[0] == image[1] && image[2] == image[3]) return 1;

	// 4: AABC
	if(image[0] == image[1] || image[1] == image[2] || image[2] == image[3]) return 2;

	return 3;
}

for(var i = 0;i < tests;i++){
	print(getMoves());
}

var x  = readline();
while(x--) {
    var first = readline(), second = readline();

    var set = new Set();

    set.add(first[0]);
    set.add(first[1]);
    set.add(second[0]);
    set.add(second[1]);

    print(set.size -1);
}

var tests = parseInt(readline());
    var a, c;
    for (var t=0; t < tests; t++) {
        a = 0;
        c = {};
        for (var i = 0; i < 2; i++) {
            var row = readline().split('');
            for (var j = 0; j < 2; j++) {
                if (!c[row[j]]) {
                    c[row[j]] = 0;
                    a++;
                }
                c[row[j]]++;
            }
        }
        print(a - 1);
    }

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

var input = '';
process.stdin.on('data', function(chunk) {
    input += chunk;
});

process.stdin.on('end', function() {
    const lines = input.trim().split('\n');
    for (let i = 1; i < lines.length; i += 2) {
        const colors = (lines[i] + lines[i + 1]).split('');
        const colorSet = new Set(colors);
        process.stdout.write(String(colorSet.size - 2) + '\n');
    }
});

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

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

function output(x) {
    if (typeof x !== 'string') {
        x = x.toString();
    }
    //process.stdout.write(x);   // without auto '\n' (newline)
    console.log(x);  // with auto '\n' (newline)
}

function main() {
    let N = readline();
    for (let test = 0; test < N; test++) {
        let pixels = readline().split('').concat(readline().split(''));
        let freq = {};

        for (let i = 0; i < 4; i++) {
            if (freq[pixels[i]]) {
                freq[pixels[i]]++;
            } else {
                freq[pixels[i]] = 1;
            }
        }

        output(Object.keys(freq).length - 1);
    }
}

let buf='';

process.stdin.on('readable',function(){
    let chunk=process.stdin.read();
    if(chunk) buf+=chunk.toString();
})

process.stdin.on('end',function(){
    const {EOL}=require('os');
    let line=buf.split(EOL);
    let t=parseInt(line[0]);
    for(let i=1;i<=t;i++)
    {
        let x=line[2*i-1];
        let y=line[2*i];
        let a=new Array(4);
        a[0]=x[0].charCodeAt();
        a[1]=x[1].charCodeAt();
        a[2]=y[0].charCodeAt();
        a[3]=y[1].charCodeAt();
        a.sort(function(x,y) {
            return x-y;
        })
        if(a[0]===a[3]) console.log(0);
        else if((a[0]==a[1]&&a[0]==a[2])||(a[1]==a[2]&&a[1]==a[3])) console.log(1);
        else if((a[0]==a[1])&&(a[2]==a[3])) console.log(1);
        else if((a[0]==a[1])||(a[1]==a[2])||(a[2]==a[3])) console.log(2);
        else console.log(3);
    }
})

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

function solve(arr) {
    const map = {}
    update(arr[0][0])
    update(arr[0][1])
    update(arr[1][0])
    update(arr[1][1])
    const ks = Object.keys(map)
    if (ks.length === 1) {
        return 0
    } else if (ks.length === 2) {
        return 1
    } else if (ks.length === 3) {
        return 2
    } else if (ks.length === 4) {
        return 3
    }
    function update(ch) {
        map[ch] = (map[ch] || 0) + 1
    }
}

// Common Template Starts //
process.stdin.resume();
process.stdin.setEncoding("utf-8");

let inputString = ""
let currentLine = 0

process.stdin.on("data", inputStdin => inputString += inputStdin)

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

const readline = () => inputString[currentLine++]
// Common Template Ends //

// Driver Function Starts //
const main = () => {
    console.clear()
    let t = parseInt(readline())
    while (t--) {
        // let n = parseInt(readline())
        let l1 = readline()
        let l2 = readline()
        console.log( solve(l1, l2) )
    }
}
// Driver Function Ends //

// MAIN LOGIC
const solve = (l1, l2) => {
    let colors = (l1+l2).split('')
    let unique = uniqueArray( colors )

    // if( unique.length == 1 ) return 0
    // if( unique.length == 2 ) return 1
    // if( unique.length == 3 ) return 2
    // if( unique.length == 4 ) return 3

    return unique.length - 1
}

const isOdd         = (num) => num & 1
const isEven        = (num) => !(num & 1)
const minOfArray    = (arr) => Math.min.apply(null, arr)
const maxOfArray    = (arr) => Math.max.apply(null, arr)
const uniqueArray   = (arr) => [...new Set(arr)]
const sortArray     = (arr) => arr.sort((a, b) => a - b)
const sumOfArray    = (arr) => arr.reduce((partialSum, a) => partialSum + a, 0)

var readline=require('readline')
var r1=readline.createInterface({
    input:process.stdin,
    output:process.stdout
})
var i=0
var t;
var a,b,c,d;
r1.question('',function (x){t=parseInt(x);test();})
async function test(){
        r1.question('',function (x){
            a=x[0]
            b=x[1]
            r1.question('',function (x){
                c=x[0]
                d=x[1]
                if(a!==b&&a!==c&&a!==d&&b!==c&&b!==d&&c!==d)
                    console.log('3\n')
                else if(a===b&&b===c&&c===d)
                    console.log('0\n')
                else if((a===b&&b===c)||(a===b&&b===d)||(a===c&&d===c)||(d===b&&b===c))
                    console.log('1\n')
                else if((a===b&&c===d)||(a===c&&b===d)||(a===d&&b===c))
                    console.log('1\n')
                else
                    console.log('2\n')
                i++;
                if(i<t)
                    test()
                else
                    r1.close()
            })
        })
}

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var set = new Set();
		for(var i = 0; i < 2; i++){
			var s = next();
			for(var j = 0; j < 2; j++){
				set.add(s[j]);
			}
		}
		myout(set.size - 1);
	}
}

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

/***
Educational Codeforces Round 134 (Div. 2)
2022-08-26

A. Image
***/

function main() {
  // INPUT: Number of test cases
  let t = readline();
  t = parseInt(t);
  for (let tc = 0; tc < t; tc++) {
    const colors = new Set();

    // INPUT: two rows with 2 colors each
    let row = readline();
    colors.add(row.charAt(0));
    colors.add(row.charAt(1));
    row = readline();
    colors.add(row.charAt(0));
    colors.add(row.charAt(1));

    console.log(colors.size - 1);
  }
}

const fs = require("fs");
const input = fs.readFileSync(0, 'utf8').trim().split('\r\n');
let currentline = 0;
function readline(){
      return input[currentline++];
}

function alph() {
  var f = 'abcdefghijklmnopqrstuvwxyz';
  return f;
}
function Alph() {
  var f = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  return f;
}
function max(x,y) {
  return x >=y ? x : y;
}
function min(x,y) {
  return x <=y ? x : y;
}
function abs(x) {
  return x < 0 ? x*(-1) : x;
}

var T = readline();
var inf = 1000000000000;
for(var tc=1;tc<=T;tc++) {
  var [n, k] = readline().split('')//.map((x) => parseInt(x));
  var [a, b] = readline().split('')//.map((x) => parseInt(x));
  var s = a+b+n+k;
  // console.log(s)
  var cnt = {
    [a]: 0,[b]:0,[n]:0,[k]:0
  }
  for(var i=0;i<4;i++) cnt[s[i]]++;
  var num = [];

  var ct = [0,0,0,0,0];
  for(var i=0;i<4;i++) {
    if(!s.slice(i+1, 4).includes(s[i])) ct[cnt[s[i]]]+=1
  }
  // console.log(cnt, ct)
  if(ct[4]) console.log(0);
  else if(ct[3]||ct[2]>1) console.log(1)
  else if(ct[2]) console.log(2);
  else console.log(3)

}

'use strict';

const fs = require('fs');

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

let inputString = '';
let currentLine = 0;

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

process.stdin.on('end', function() {
    inputString = inputString.split('\n');

    main();
});

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

function isPossible(n, x, heights) {
    heights.sort();
    heights.sort(function(a, b) {
        return a - b;
      });
    // //console.log(heights)

    let front = []
    let back = []

    for (let i = 0; i < heights.length; i++) {
        if (i < n) {
            front.push(heights[i])
        } else {
            back.push(heights[i])
        }
    }

    // //console.log(front)
    // //console.log(back)
    for (let j = 0; j < front.length; j++) {
        if (back[j] - front[j] < x) {
            // //console.log(back[j] + " " + front[j])
            return "NO";
        }
    }

    return "YES";
}

function calc(a, m) {
    let s = "";
    for (let index = 0; index < m; index++) {
        s += "B"
    }

   for (let index = 0; index < a.length; index++) {
        let ai = a[index];

        if (ai < (m + 1 - ai)) {
            let _s = s.replaceAt(ai - 1, "A");
            if (compare(_s, s) < 0) {
                s = _s;
                continue;
            } else if (compare(_s, s) >= 0) {
                    let __ss = s.replaceAt(m + 1 - ai - 1, "A");
                    if (compare(__ss, s) < 0) {
                        s = __ss;
                        continue;
                    }
            }
         }  else {
            let _s = s.replaceAt(m + 1 - ai - 1, "A");
            if (compare(_s, s) < 0) {
                s = _s;
                continue;
            }  if (compare(_s, s) >= 0) {
                    let __ss = s.replaceAt(ai - 1, "A");
                    if (compare(__ss, s) < 0) {
                        s = __ss;
                        continue;
                    }
            }
    }
}

   return s;
}

function compare(s1, s2) {
    return s1.localeCompare(s2)
}

String.prototype.replaceAt = function(index, replacement) {
    return this.substring(0, index) + replacement + this.substring(index + replacement.length);
}

function main() {
    const test_cases = parseInt(readLine().trim(), 10);

    for (let gItr = 0; gItr < test_cases; gItr++) {
        // const arr1 = readLine().replace(/\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));
        // const arr2 = readLine().replace(/\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));
        const line1 = readLine().trim()
        const line2 = readLine().trim()
        const color1 = line1[0]
        const color2 = line1[1]
        const color3 = line2[0]
        const color4 = line2[1]

        let mySet = new Set()
        mySet.add(color1)
        mySet.add(color2)
        mySet.add(color3)
        mySet.add(color4)

        if (mySet.size == 4) {
            console.log(3)
        } else if (mySet.size == 3) {
            console.log(2)
        } else if (mySet.size == 2) {
            console.log(1)
        } else if (mySet.size == 1) {
            console.log(0)
        }
    }

    // ws.end();
}

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

let input = [];
rl.on("line", function (line) {
  input.push(line);

  if (input.length === +input[0] * 2 + 1) {
    // call your function here
    solve(input);
    rl.close();
  }
});

let solve = (input) => {
  let set = new Set();

  for (let i = 1; i < input.length; i += 2) {
    let colors = input[i].split("");
    set.add(colors[0]);
    set.add(colors[1]);
    colors = input[i + 1].split("");
    set.add(colors[0]);
    set.add(colors[1]);

    if (set.size === 1) console.log(0);
    if (set.size === 4) console.log(3);
    if (set.size === 2) console.log(1);
    if (set.size === 3) console.log(2);
    set.clear();
  }
};

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

function main() {
    const t = +readLine();
    for(let i = 0; i < t; i++){
        // const n = +readLine();
        const ab = readLine();
        const cd = readLine();
        let result = myFunc(ab[0], ab[1], cd[0], cd[1]);
        console.log(result);
    }
}

function myFunc(a, b, c, d){

    let set = new Set();
    set.add(a);
    set.add(b);
    set.add(c);
    set.add(d);

    if(set.size == 1) return 0;
    if(set.size == 2) return 1;
    if(set.size == 3) return 2;
    if(set.size == 4) return 3;

}

let fs = require("fs");
let sc = {
    _buf: new Buffer.alloc(1 << 14),
    _bufPos: 0,
    _bufLen: 0,
    _ensure: function ()
    {
        if (this._bufPos === this._bufLen)
        {
            this._bufPos = 0;
            this._bufLen = fs.readSync(0, this._buf, 0, this._buf.length, null);
        }
    },
    _isws: function (ch)
    {
        return ch === 32 || ch === 9 || ch === 10 || ch === 13;
    },
    _islf: function (ch)
    {
        return ch === 10 || ch === 13;
    },
    _peekChar: function ()
    {
        this._ensure();
        return this._bufPos === this._bufLen ? 0 : this._buf[this._bufPos];
    },
    _skipWs: function ()
    {
        while (this._isws(this._peekChar()))
            this._bufPos++;
    },
    _readUntil: function (stop)
    {
        this._ensure();
        if (this._bufPos === this._bufLen)
            throw new Error("eof");
        let start = this._bufPos;
        let before = null;
        for (; ;)
        {
            if (this._bufPos === this._bufLen)
            {
                let len = this._bufPos - start, preLen = (before ? before.length : 0);
                let nbuf = new Buffer(len + preLen);
                if (before)
                    before.copy(nbuf);
                before = nbuf;
                this._buf.copy(before, preLen, start);
                this._ensure();
                start = this._bufPos;
            }
            if (this._bufPos === this._bufLen || stop(this._buf[this._bufPos])) break;
            this._bufPos++;
        }
        if (!before)
            return this._buf.toString("utf8", start, this._bufPos);
        let after = this._buf.slice(start, this._bufPos);
        let res = new Buffer(before.length + after.length);
        before.copy(res);
        after.copy(res, before.length);
        return res.toString();
    },

    nextToken: function ()
    {
        this._skipWs();
        return this._readUntil(this._isws);
    },
    L: function ()
    {
        let line = this._readUntil(this._islf);
        if (this._peekChar() === 13) this._bufPos++;
        if (this._peekChar() === 10) this._bufPos++;
        return line;
    },
    N: function ()
    {
        return +this.nextToken();
    },
    S: function ()
    {
        return this.nextToken();
    }
};

// DO NOT CHANGE TEMPLATE BEFORE

const Def = Number(1e9);

const Solve = () =>
{
    let s = sc.S() + sc.S();
    // console.log(`s = ${s}`);

    let count = 0, map = new Map();
    for (let ch of s)
    {
        if (!map.has(ch))
        {
            ++count;
            map.set(ch, 1);
        }
    }

    console.log(count - 1);

}

const main = () =>
{
    let cases = sc.N();
    while (cases-- > 0) Solve();

    // Solve();
}
main();

const fs = require("fs");

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

const testCases = [];
let T;

function parseInput() {
  T = parseInt(input[0]);
  let index = 0;

  for (let i = 0; i < T; i++) {
    index++;
    const [a, b] = input[index].split("");
    index++;
    const [c, d] = input[index].split("");
    const testCase = {
      a: [a, b, c, d],
    };

    testCases.push(testCase);
  }
}

function solution(testCase) {
  const { a } = testCase;
  // console.log(a);

  const dict = {};
  a.forEach((v) => {
    if (!dict[v]) dict[v] = 0;
    dict[v]++;
  });

  const b = Object.values(dict).sort((c, d) => c - d);
  // console.error(b);

  console.log(b.length - 1);
}

parseInput();

testCases.forEach(solution);

const t = Number(readline());
// const t = Number('5');
// print(t);

// const inputValues = ['rb', 'br', 'cc', 'wb', 'aa', 'aa', 'ab', 'cd', 'yy', 'xx'];

for (i = 0; i < t; i++) {
  //   const currentImage = inputValues[i * 2] + inputValues[i * 2 + 1];
  currentImage = readline() + readline();
  print(currentImage);

  uniqueColors = new Set(currentImage.split(''));
  nrOfUniqueColors = [...uniqueColors].length;

  //   console.log(nrOfUniqueColors - 1);
  print(nrOfUniqueColors - 1);
}

const t = Number(readline());
// const t = Number('5');
// print(t);

// const inputValues = ['rb', 'br', 'cc', 'wb', 'aa', 'aa', 'ab', 'cd', 'yy', 'xx'];

for (i = 0; i < t; i++) {
  //   const currentImage = inputValues[i * 2] + inputValues[i * 2 + 1];
  const currentImage = readline() + readline();
  print(currentImage);

  const uniqueColors = new Set(currentImage.split(''));
  const nrOfUniqueColors = [...uniqueColors].length;

  //   console.log(nrOfUniqueColors - 1);
  print(nrOfUniqueColors - 1);
}

const t = Number(readline());
// const t = Number('5');
// print(t);

// const inputValues = ['rb', 'br', 'cc', 'wb', 'aa', 'aa', 'ab', 'cd', 'yy', 'xx'];

for (i = 0; i < t; i++) {
  //   const currentImage = inputValues[i * 2] + inputValues[i * 2 + 1];
  const currentImage = readline() + readline();
  // print(5);

  const uniqueColors = new Set(currentImage.split(''));
  const nrOfUniqueColors = [...uniqueColors].length;

  //   console.log(nrOfUniqueColors - 1);
  print(nrOfUniqueColors - 1);
}

const t = Number(readline());
// const t = Number('5');
print(t);

// const inputValues = ['rb', 'br', 'cc', 'wb', 'aa', 'aa', 'ab', 'cd', 'yy', 'xx'];

// for (let i = 0; i < t; i++) {
//   const currentImage = inputValues[i * 2] + inputValues[i * 2 + 1];
// const currentImage = readline() + readline();
// print(5);

//   const uniqueColors = new Set(currentImage.split(''));
//   const nrOfUniqueColors = [...uniqueColors].length;

//   console.log(nrOfUniqueColors - 1);
//   // print(nrOfUniqueColors - 1);
// }

for (i = 0; i < t; i++) {
  print(t);
}

const t = Number(readline());
// const t = Number('5');
print(t);

// const inputValues = ['rb', 'br', 'cc', 'wb', 'aa', 'aa', 'ab', 'cd', 'yy', 'xx'];

// for (let i = 0; i < t; i++) {
//   const currentImage = inputValues[i * 2] + inputValues[i * 2 + 1];
// const currentImage = readline() + readline();
print(5);

//   const uniqueColors = new Set(currentImage.split(''));
//   const nrOfUniqueColors = [...uniqueColors].length;

//   console.log(nrOfUniqueColors - 1);
//   // print(nrOfUniqueColors - 1);
// }

const t = Number(readline());
// const t = Number('5');
print(t);

// const inputValues = ['rb', 'br', 'cc', 'wb', 'aa', 'aa', 'ab', 'cd', 'yy', 'xx'];

// for (let i = 0; i < t; i += 1) {
//   const currentImage = inputValues[i * 2] + inputValues[i * 2 + 1];
//   // const currentImage = readline() + readline();

//   const uniqueColors = new Set(currentImage.split(''));
//   const nrOfUniqueColors = [...uniqueColors].length;

//   console.log(nrOfUniqueColors - 1);
//   // print(nrOfUniqueColors - 1);
// }

var repeatTimes = readline();

while (repeatTimes--) {
    var str1 = readline()
    var str2 = readline()
    var set1 = new Set()
    set1.add(str1[0])
    set1.add(str1[1])
    set1.add(str2[0])
    set1.add(str2[1])
    print(set1.size)
}

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

var input = '';
process.stdin.on('data', function(chunk) {
    input += chunk;
});

process.stdin.on('end', function() {
    const lines = input.trim().split('\n');
    for (let i = 1; i < lines.length; i += 2) {
        const colors = (lines[i] + lines[i + 1]).split('');
        const colorSet = new Set(colors);
        process.stdout.write(String(colorSet.size - 1) + '\n');
    }
});

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

var input = '';
process.stdin.on('data', function(chunk) {
    input += chunk;
});

process.stdin.on('end', function() {
    const lines = input.trim().split('\n');
    for (let i = 1; i < lines.length; i += 2) {
        const colors = (lines[i] + lines[i + 1]).split('');
        const colorSet = new Set(colors);
        console.log(String(colorSet.size - 1));
    }
});

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

var input = '';
process.stdin.on('data', function(chunk) {
    input += chunk;
});

process.stdin.on('end', function() {
    const lines = input.trim().split('\n');
    for (let i = 1; i < lines.length; i += 2) {
        const colors = (lines[i] + lines[i + 1]).split('');
        const colorSet = new Set(colors);
        console.log(colorSet.size - 1);
    }
});

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

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

function output(x) {
    if (typeof x !== 'string') {
        x = x.toString();
    }
    //process.stdout.write(x);   // without auto '\n' (newline)
    console.log(x);  // with auto '\n' (newline)
}

function main() {
    let N = readline();
    for (let test = 0; test < N; test++) {
        let pixels = readline().split('').concat(readline().split(''));
        let freq = {};

        for (let i = 0; i < 4; i++) {
            if (freq[pixels[i]]) {
                freq[pixels[i]]++;
            } else {
                freq[pixels[i]] = 1;
            }
        }

        const count = Object.keys(freq).length;
        let values = Object.keys(freq).map(key => freq[key]);

        if (count === 1) {
            output(0);
        } else if (count === 2) {
            if (values.includes(3)) {
                output(3);
            } else {
                output(2);
            }
        } else if (count === 3) {
            output(3);
        } else if (count === 4) {
            output(4);
        }
    }
}