Given $$$n$$$ strings, each of length $$$2$$$, consisting of lowercase Latin alphabet letters from 'a' to 'k', output the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and the $$$i$$$-th string and the $$$j$$$-th string differ in exactly one position.In other words, count the number of pairs $$$(i, j)$$$ ($$$i < j$$$) such that the $$$i$$$-th string and the $$$j$$$-th string have exactly one position $$$p$$$ ($$$1 \leq p \leq 2$$$) such that $$${s_{i}}_{p} \neq {s_{j}}_{p}$$$.The answer may not fit into 32-bit integer type, so you should use 64-bit integers like long long in C++ to avoid integer overflow.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of strings. Then follows $$$n$$$ lines, the $$$i$$$-th of which containing a single string $$$s_i$$$ of length $$$2$$$, consisting of lowercase Latin letters from 'a' to 'k'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print a single integer — the number of pairs $$$(i, j)$$$ ($$$i < j$$$) such that the $$$i$$$-th string and the $$$j$$$-th string have exactly one position $$$p$$$ ($$$1 \leq p \leq 2$$$) such that $$${s_{i}}_{p} \neq {s_{j}}_{p}$$$.  Please note, that the answer for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).

4
6
ab
cb
db
aa
cc
ef
7
aa
bb
cc
ac
ca
bb
aa
4
kk
kk
ab
ab
5
jf
jf
jk
jk
jk

NoteFor the first test case the pairs that differ in exactly one position are: ("ab", "cb"), ("ab", "db"), ("ab", "aa"), ("cb", "db") and ("cb", "cc").For the second test case the pairs that differ in exactly one position are: ("aa", "ac"), ("aa", "ca"), ("cc", "ac"), ("cc", "ca"), ("ac", "aa") and ("ca", "aa").For the third test case, the are no pairs satisfying the conditions.

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let n = parseInt(readline());
    let arr = [];
    for (let i = 0; i < n; i++) {
      arr.push(readline().trim());
    }
    if (n === 1) {
      console.log("0");
      continue;
    }
    let alp = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"];
    let obj = {};
    obj[arr[n - 1]] = 1;
    let sum = 0;
    for (let i = n - 2; i >= 0; i--) {
      let k = arr[i][1];
      for (let j = 0; j < alp.length; j++) {
        if (alp[j] !== k) {
          if (obj[arr[i][0] + alp[j]]) sum += obj[arr[i][0] + alp[j]];
        }
      }
      k = arr[i][0];
      for (let j = 0; j < alp.length; j++) {
        if (alp[j] !== k)
          if (obj[alp[j] + arr[i][1]]) sum += obj[alp[j] + arr[i][1]];
      }
      if (obj[arr[i]]) obj[arr[i]] += 1;
      else obj[arr[i]] = 1;
    }
    console.log(sum);
  }
};
solve();

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

function readline() {
    return inputString[currentLine++];
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {
    const T = readline();
    for (let i = 0; i < T; i++) {
        const n = readline()
        let arr = []
        for (let j = 0; j < n; j++) {
            arr.push(readline())
        }
        solve(arr)
    }
}
function solve(arr) {
    let tot = 0
    let map = new Map()
    for (let i = arr.length - 1; i >=0 ; i--) {
        let pos = arr.length
        let cnt = 0
        if (map.has(arr[i])) {
            [pos, cnt] = map.get(arr[i])
        }

        let s1 = arr[i]
        for (let j = i + 1; j < pos; j++) {
            let s2 = arr[j]
            if (s1[0] === s2[0] && s1[1] !== s2[1] || s1[0] !== s2[0] && s1[1] === s2[1]) {
                cnt++;
            }
        }

        tot += cnt
        map.set(arr[i], [i, cnt])

    }

    console.log(tot)
}

'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++];
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {
  let _t = parseInt(readline());
  // let _t = 1;
  while (_t--) {
    let n = parseInt(readline());
    let m = [],
      a = [];
    for (let i = 0; i < n; i++) {
      let s = readline();
      a.push(s);
      if (m[s]) m[s]++;
      else m[s] = 1;
    }
    let ans = 0;
    a.forEach((e) => {
      for (let i = 9; i < 36; i++) {
        let c = i.toString(36);
        if (c === e[0]) continue;
        let cur = c + e[1];
        ans += m[cur] ? m[cur] : 0;
      }
      for (let i = 9; i < 36; i++) {
        let c = i.toString(36);
        if (c === e[1]) continue;
        let cur = e[0] + c;
        // console.log(cur);
        ans += m[cur] ? m[cur] : 0;
      }
    });
    console.log(ans / 2);
  }
}

// cat input.txt | node main.js

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 calc = (n, a)=>{
    let chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'];
    let result = BigInt(0);

    let mapStart = {};
    let mapEnd = {};
    let mapBoth = {};

    for (let i = 0; i < n; i++) {
        // mapStart[a[i][0]] = (mapStart[a[i][0]] || 0) + 1;
        // mapEnd[a[i][1]] = (mapEnd[a[i][1]] || 0) + 1;

        // pairs like a[i][0] + chars[j]
        for (let j = 0; j < chars.length; j++) {
            if (chars[j] === a[i][1]) continue;
            result += mapBoth[`${a[i][0]}${chars[j]}`] || 0n;
        }

        // pairs like chars[j] + a[i][1]
        for (let j = 0; j < chars.length; j++) {
            if (chars[j] === a[i][0]) continue;
            result += mapBoth[`${chars[j]}${a[i][1]}`] || 0n;
        }

        mapBoth[a[i]] = (mapBoth[a[i]] || 0n) + 1n;
    }

    // console.log(`DEBUG mapStart`, mapStart);
    // console.log(`DEBUG mapEnd`, mapEnd);
    // console.log(`DEBUG mapBoth`, mapBoth);

    // for (let i = 0; i < chars.length; i++) {
    //     for (let j = i; j < chars.length; j++) {
    //         if (mapStart[chars[i]]) result += BigInt(cnk(mapStart[chars[i]], 2));
    //         if (mapEnd[chars[j]]) result += BigInt(cnk(mapEnd[chars[j]], 2));
    //         let pair = `${chars[i]}${chars[j]}`;
    //         if (mapBoth[pair]) result -= BigInt(2 * cnk(mapBoth[pair], 2));
    //     }
    //     console.log(`DEBUG result for ${i}`, result);
    // }

    return result;
};

function main() {
    let T = +readline();
    for (let t = 1; t <= T; t++){
        let n = +readline();
        let a = [];
        for (let i = 0; i < n; i++) {
            a.push(readline());
        }
        console.log(`${calc(n, a)}`);
    }
}

'use strict';
 /*jslint node:true, browser:true, es6:true*/
const print = console.log
const E = {};
const lines = []
if (!process.env.JEST_WORKER_ID){
  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 L = process.env.DEBUG ? console.log : ()=>{};

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

let ca = "a".charCodeAt(0);
const compose = (n0, n1)=>{
  return (1<<n0)|(1<<(11+n1))
};
const calc = (n, A)=>{
  let map = new Map();
  let ans = 0;
  for (let s of A){
    L({s})
    let n0 = s.charCodeAt(0)-ca;
    let n1 = s.charCodeAt(1)-ca;
    for (let i=0; i<=10; i++){
      if (i!=n0){
        let a = compose(i, n1);
        ans += map.get(a)||0;
        if (map.get(a))
          L('ADD1', a.toString(2), map.get(a))
      }
      if (i!=n1){
        let a = compose(n0, i);
        ans += map.get(a)||0;
        if (map.get(a))
          L('ADD2', a.toString(2), map.get(a))
      }
    }
    let a = compose(n0, n1);
    map.set(a, (map.get(a)||0)+1)
    L('SET', a.toString(2), 1)
  }
  return ans;
};

function main() {
    let T = +readline()
    while (T--){
      let [n] = ra();
      let A = [];
      for (let i=0; i<n; i++)
        A.push(readline())
      L('Ans:')
      print(calc(n, A));
    }
}

E.calc = calc;

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

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

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

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

		let ans = 0;
		const cnt = [];
		const cntFirst = [];
		const cntSecond = [];
		for (let i = 0; i < n; i++) {
			const s = rl();
			cnt[s] = cnt[s] || 0;
			cntFirst[s[0]] = cntFirst[s[0]] || 0;
			cntSecond[s[1]] = cntSecond[s[1]] || 0;

			ans += cntFirst[s[0]] - cnt[s];
			ans += cntSecond[s[1]] - cnt[s];
			cntFirst[s[0]]++;
			cntSecond[s[1]]++;
			cnt[s]++;
		}

		console.log(ans);
	}
}

'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(a) {
  const map = new Map();
  const get = char => char.charCodeAt(0) - 97;
  let res = 0n;
  for (let [l, r] of a) {
    var _map$get, _map$get2, _map$get3, _map$get4, _map$get5, _map$get6;
    let statel = 1 << get(l),
        stater = 1 << get(r) + 11,
        state = statel | stater;
    res = res + ((_map$get = map.get(statel)) !== null && _map$get !== void 0 ? _map$get : 0n) + ((_map$get2 = map.get(stater)) !== null && _map$get2 !== void 0 ? _map$get2 : 0n) - ((_map$get3 = map.get(state)) !== null && _map$get3 !== void 0 ? _map$get3 : 0n) * 2n;
    map.set(statel, ((_map$get4 = map.get(statel)) !== null && _map$get4 !== void 0 ? _map$get4 : 0n) + 1n);
    map.set(stater, ((_map$get5 = map.get(stater)) !== null && _map$get5 !== void 0 ? _map$get5 : 0n) + 1n);
    map.set(state, ((_map$get6 = map.get(state)) !== null && _map$get6 !== void 0 ? _map$get6 : 0n) + 1n);
  }
  console.log(res.toString());
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    let n = Number(await read()),
        a = [];
    while (n--) {
      a.push(await read());
    }
    solve(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);
}();

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var list = nextStrArray(N);
		var map = {};
		var alpha = "abcdefghijk";
		for(var i = 0; i < alpha.length; i++){
			for(var j = 0; j < alpha.length; j++){
				map[alpha[i] + alpha[j]] = 0;
			}
		}
		for(var i = 0; i < N; i++){
			map[list[i]]++;
		}

		var output = 0n;
		var key = Object.keys(map);
		for(var i = 0; i < key.length; i++){
			for(var j = i + 1; j < key.length; j++){
				var Li = key[i][0];
				var Ri = key[i][1];
				var Lj = key[j][0];
				var Rj = key[j][1];
				if(Li == Lj || Ri == Rj){
					output += BigInt(map[key[i]] * map[key[j]]);
				}
			}
		}
		myout(output);
	}
}

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

function solve(n, arr) {
    n = BigInt(n)
    //
    const map = {}
    arr.forEach(x => {
        const [a, b] = x
        map[a] = map[a] || {}
        map[a][b] = (map[a][b] || 0n) + 1n
    })
// console.log(map)
// // return
    const chs = 'abcdefghijk'
    let diff = 0n
    let same = 0n
    // [i, j] [u, v]
    for (let i = 0; i < chs.length; i++) {
    for (let j = 0; j < chs.length; j++) {
        const y = cal(map, chs[i], chs[j])
        same += y * (y - 1n)
    for (let u = 0; u < chs.length; u++) {
        if (u === i) continue
    for (let v = 0; v < chs.length; v++) {
        if (v === j) continue
        const x = cal(map, chs[u], chs[v])
        diff += x * y
    }
    }
    }
    }
    const total = (n - 1n) * n
// console.log(total, diff, same)
    return (total - diff - same) / 2n
}
function cal(map, i, j) {
    return (map[i] && map[i][j]) ? map[i][j] : 0n
}

"use strict";
const fs = require("fs");
const { consumers } = require("stream");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let n = parseInt(readline());
    let arr = [];
    for (let i = 0; i < n; i++) {
      arr.push(readline().trim().split(""));
    }
    if(n===1) {
      console.log("0");
      continue;
    }
    let alp = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"];
    let narr = [];
    let obj = {};
    for (let i = 0; i < alp.length; i++) {
      let na = [];
      for (let j = 0; j < n; j++) {
        for (let k = 0; k < 2; k++) {
          if (arr[j][k] === alp[i]) {
            na.push(arr[j]);
            break;
          }
        }
      }
      narr.push(na);
    }
    let res = 0n;
    for (let i = 0; i < 11; i++) {
      if (narr[i].length >= 2) {
        let obj = {};
        let len = BigInt(narr[i].length);
        let sum = 0n;
        for (let j = narr[i].length - 1; j >= 0; j--) {
          let s1 = narr[i][j][0] + narr[i][j][1];
          let s2 = narr[i][j][1] + narr[i][j][0];
          if (obj[s1] || obj[s2]) {
            obj[s1]++;
          } else {
            obj[s1] = 1n;
            obj[s2] = 1n;
          }
          if (obj[s1] === 1) sum += len - (BigInt(j) + 1n);
          else sum += len - (BigInt(j) + 1n) - (obj[s1] - 1n);
        }
        res += sum;
      }
    }
    console.log(res + "");
  }
};
solve();

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 calc = (n, a)=>{
    let chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'];
    let result = BigInt(0);

    let mapStart = {};
    let mapEnd = {};
    let mapBoth = {};

    for (let i = 0; i < n; i++) {
        // mapStart[a[i][0]] = (mapStart[a[i][0]] || 0) + 1;
        // mapEnd[a[i][1]] = (mapEnd[a[i][1]] || 0) + 1;

        // pairs like a[i][0] + chars[j]
        for (let j = 0; j < chars.length; j++) {
            if (chars[j] === a[i][1]) continue;
            result += BigInt(mapBoth[`${a[i][0]}${chars[j]}`] || 0);
        }

        // pairs like chars[j] + a[i][1]
        for (let j = 0; j < chars.length; j++) {
            if (chars[j] === a[i][0]) continue;
            result += BigInt(mapBoth[`${chars[j]}${a[i][1]}`] || 0);
        }

        mapBoth[a[i]] = (mapBoth[a[i]] || 0) + 1;
    }

    // console.log(`DEBUG mapStart`, mapStart);
    // console.log(`DEBUG mapEnd`, mapEnd);
    // console.log(`DEBUG mapBoth`, mapBoth);

    // for (let i = 0; i < chars.length; i++) {
    //     for (let j = i; j < chars.length; j++) {
    //         if (mapStart[chars[i]]) result += BigInt(cnk(mapStart[chars[i]], 2));
    //         if (mapEnd[chars[j]]) result += BigInt(cnk(mapEnd[chars[j]], 2));
    //         let pair = `${chars[i]}${chars[j]}`;
    //         if (mapBoth[pair]) result -= BigInt(2 * cnk(mapBoth[pair], 2));
    //     }
    //     console.log(`DEBUG result for ${i}`, result);
    // }

    return result;
};

function main() {
    let T = +readline();
    for (let t = 1; t <= T; t++){
        let n = +readline();
        let a = [];
        for (let i = 0; i < n; i++) {
            a.push(readline());
        }
        console.log(`${calc(n, a)}`);
    }
}

'use strict';
 /*jslint node:true, browser:true, es6:true*/
const print = console.log
const E = {};
const lines = []
if (!process.env.JEST_WORKER_ID){
  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 L = process.env.DEBUG ? console.log : ()=>{};

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

let ca = "a".charCodeAt(0);
const compose = (n0, n1)=>{
  return (1<<n0)|(1<<(11+n1))
};
const calc = (n, A)=>{
  let map = new Map();
  let ans = 0;
  for (let s of A){
    L({s})
    let n0 = s.charCodeAt(0)-ca;
    let n1 = s.charCodeAt(1)-ca;
    for (let i=0; i<10; i++){
      if (i!=n0){
        let a = compose(i, n1);
        ans += map.get(a)||0;
        if (map.get(a))
          L('ADD1', a.toString(2), map.get(a))
      }
      if (i!=n1){
        let a = compose(n0, i);
        ans += map.get(a)||0;
        if (map.get(a))
          L('ADD2', a.toString(2), map.get(a))
      }
    }
    let a = compose(n0, n1);
    map.set(a, (map.get(a)||0)+1)
    L('SET', a.toString(2), 1)
  }
  return ans;
};

function main() {
    let T = +readline()
    while (T--){
      let [n] = ra();
      let A = [];
      for (let i=0; i<n; i++)
        A.push(readline())
      L('Ans:')
      print(calc(n, A));
    }
}

E.calc = calc;


Inna loves digit 9 very much. That's why she asked Dima to write a small number consisting of nines. But Dima must have misunderstood her and he wrote a very large number a, consisting of digits from 1 to 9.Inna wants to slightly alter the number Dima wrote so that in the end the number contained as many digits nine as possible. In one move, Inna can choose two adjacent digits in a number which sum equals 9 and replace them by a single digit 9.For instance, Inna can alter number 14545181 like this: 14545181 → 1945181 → 194519 → 19919. Also, she can use this method to transform number 14545181 into number 19991. Inna will not transform it into 149591 as she can get numbers 19919 and 19991 which contain more digits nine.Dima is a programmer so he wants to find out how many distinct numbers containing as many digits nine as possible Inna can get from the written number. Help him with this challenging task.

The first line of the input contains integer a (1 ≤ a ≤ 10100000). Number a doesn't have any zeroes.

In a single line print a single integer — the answer to the problem. It is guaranteed that the answer to the problem doesn't exceed 263 - 1. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteNotes to the samplesIn the first sample Inna can get the following numbers: 369727 → 99727 → 9997, 369727 → 99727 → 9979.In the second sample, Inna can act like this: 123456789987654321 → 12396789987654321 → 1239678998769321.

var SIZE = 100100;

function main() {
    var line = "9" + readline() + "9";
    line = line.split('').map(function(item) {
        return parseInt(item, 10);
    });

    var res = 1;
    var cnt = 1;
    for (var i = 1; i < line.length; i++) {
        // print(line[i-1], line[i]);
        if (line[i-1] + line[i] == 9) {
            cnt += 1
        } else {
            if (cnt > 1 && cnt % 2 == 1) res *= Math.floor(cnt/2) + 1;
            cnt = 1;
        }
        // print(cnt);
    }
    print(res);
}

main();

var SIZE = 100100;

function main() {
    var line = readline();
    var A = new Array(0, 0, 0);

    for (var i = 1; i < line.length; i++) {
        A[0] = Math.max(A[0], A[1]);
        A[1] = A[2];
        A[2] = 0;

        if (parseInt(line[i]) + parseInt(line[i - 1]) == 9) {
            A[2]++;
            A[2] += A[0];
        }
    }
    var max_nine = Math.max.apply(Math, A);

    var ans = 0;
    var B = new Array(0, 0, 0);
    var M = new Array(1, 0, 0);
    var method = 0;
    for (var i = 1; i < line.length; i++) {
        if (B[1] > B[0]) {
            B[0] = Math.max(B[0], B[1]);
            M[0] = M[1];
        }
        B[1] = B[2];
        M[1] = M[2];
        B[2] = 0;
        M[2] = 0;

        if (parseInt(line[i]) + parseInt(line[i - 1]) == 9) {
            B[2] += B[0] + 1;
            M[2] = M[0];
        }

        if (B[2] == max_nine) {
            method += M[2];
        }
    }

    print(method);
}

main();

var SIZE = 100100;

function main() {
    var line = readline();
    var A = new Array(0, 0, 0);

    for (var i = 1; i < line.length; i++) {
        // print(A);
        A[0] = Math.max(A[0], A[1]);
        A[1] = A[2];
        A[2] = 0;

        if (parseInt(line[i]) == 9) {
            A[2] += Math.max(A[0], A[1]) + 1;
        } else if (parseInt(line[i]) + parseInt(line[i - 1]) == 9) {
            A[2]++;
            A[2] += A[0];
        }

    }
    print(Math.max.apply(Math, A));
}

main();

var SIZE = 100100;

function main() {
    var line = readline();
    var A = new Array(0, 0, 0);

    for (var i = 1; i < line.length; i++) {
        // print(A);
        A[0] = Math.max(A[0], A[1]);
        A[1] = A[2];
        A[2] = 0;

        if (parseInt(line[i]) + parseInt(line[i - 1]) == 9) {
            A[2]++;
            A[2] += A[0];
        }

    }
    print(Math.max.apply(Math, A));
}

main();


Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play $$$t$$$ matches of a digit game...In each of $$$t$$$ matches of the digit game, a positive integer is generated. It consists of $$$n$$$ digits. The digits of this integer are numerated from $$$1$$$ to $$$n$$$ from the highest-order digit to the lowest-order digit. After this integer is announced, the match starts.Agents play in turns. Raze starts. In one turn an agent can choose any unmarked digit and mark it. Raze can choose digits on odd positions, but can not choose digits on even positions. Breach can choose digits on even positions, but can not choose digits on odd positions. The match ends, when there is only one unmarked digit left. If the single last digit is odd, then Raze wins, else Breach wins.It can be proved, that before the end of the match (for every initial integer with $$$n$$$ digits) each agent has an ability to make a turn, i.e. there is at least one unmarked digit, that stands on a position of required parity.For each of $$$t$$$ matches find out, which agent wins, if both of them want to win and play optimally.

First line of input contains an integer $$$t$$$ $$$(1 \le t \le 100)$$$  — the number of matches. The first line of each match description contains an integer $$$n$$$ $$$(1 \le n \le 10^3)$$$  — the number of digits of the generated number. The second line of each match description contains an $$$n$$$-digit positive integer without leading zeros.

For each match print $$$1$$$, if Raze wins, and $$$2$$$, if Breach wins.

NoteIn the first match no one can make a turn, the only digit left is $$$2$$$, it's even, so Breach wins.In the second match the only digit left is $$$3$$$, it's odd, so Raze wins.In the third match Raze can mark the last digit, after that Breach can only mark $$$0$$$. $$$1$$$ will be the last digit left, it's odd, so Raze wins.In the fourth match no matter how Raze plays, Breach can mark $$$9$$$, and in the end there will be digit $$$0$$$. It's even, so Breach wins.

let readline=require('readline');
let rl=readline.createInterface({
    input:process.stdin,
    output:process.stdout
});
let arr=[],T;
rl.on('line',function(inp){
    arr.push(inp);
    let len=arr.length;
    if(len===1) T=parseInt(arr[0]);
    else if(len===2*T+1){
        for(let i=2;i<=2*T;i+=2){
            let l=arr[i].length;
            if(l%2){
                let flag=0;
                for(let j=0;j<l;j+=2){
                    if(parseInt(arr[i][j])%2){
                        flag=1;
                        break;
                    }
                }
                if(flag) console.log(1);
                else console.log(2);
            }else{
                let flag=0;
                for(let j=1;j<l;j+=2){
                    if(parseInt(arr[i][j])%2===0){
                        flag=1;
                        break;
                    }
                }
                if(flag) console.log(2);
                else console.log(1);
            }
        }
        process.exit(0);
    }
});

const main = async () => {
    const inputs = [];
    let times = null;

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

    for await (const line of rl) {
      if (!times) {
        times = line;
      } else {
        if (inputs.length < times * 2 - 1) {
          inputs.push(line);
        } else {
          inputs.push(line);
          rl.close();
        }
      }
    }

    runGame(times, inputs);
  };

  const runGame = (times, inputs) => {
    for (let i = 0; i < times; i++) {
      findMatch(inputs[i * 2], inputs[i * 2 + 1]); // len, digits
    }
  };

  const findMatch = (len, digits) => {
    const arr = digits.toString(10).split("").map(Number);
    let output = 0;

    if (len % 2 === 0) {
      for (let evenIndex = 0; evenIndex < +len / 2; evenIndex++) {
        if (arr[2 * evenIndex + 1] % 2 === 0) output++;
      }
      if (output > 0) {
        console.log("2");
      } else {
        console.log("1");
      }
    } else {
      output = 0;

      for (let oddIndex = 0; oddIndex < (+len + 1) / 2; oddIndex++) {
        if (arr[(2 * oddIndex)] % 2 !== 0) output++;
      }
      if (output > 0) {
        console.log("1");
      } else {
        console.log("2");
      }
    }
  };

  main();

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 main() {
  let t = +readLine();
  while (t--) {
    const len = +readLine();
    const str = readLine();
    let win = false;

    if (len % 2 === 1) {
      for (let i = 0; i < len; i += 2) {
        if (+str[i] % 2 === 1) {
          win = true;
          break;
        }
      }
      if (win) console.log(1);
      else console.log(2);
    } else {
      for (let i = 1; i < len; i += 2) {
        if (+str[i] % 2 === 0) {
          win = true;
          break;
        }
      }
      if (win) console.log(2);
      else console.log(1);
    }
  }
}

// Digit Game - https://codeforces.com/problemset/problem/1419/A

const main = async () => {
  const inputs = [];
  let times = null;

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

  for await (const line of rl) {
    if (!times) {
      times = line;
    } else {
      if (inputs.length < times * 2 - 1) {
        inputs.push(line);
      } else {
        inputs.push(line);
        rl.close();
      }
    }
  }

  runGame(times, inputs);
};

const runGame = (times, inputs) => {
  for (let i = 0; i < times; i++) {
    findMatch(inputs[i * 2], inputs[i * 2 + 1]); // len, digits
  }
};

const findMatch = (len, digits) => {
  const arr = digits.toString(10).split("").map(Number);
  let output = 0;

  if (len % 2 === 0) {
    for (let evenIndex = 0; evenIndex < +len / 2; evenIndex++) {
      if (arr[2 * evenIndex + 1] % 2 === 0) output++;
    }
    if (output > 0) {
      console.log("2");
    } else {
      console.log("1");
    }
  } else {
    output = 0;

    for (let oddIndex = 0; oddIndex < (+len + 1) / 2; oddIndex++) {
      if (arr[2 * oddIndex] % 2 !== 0) output++;
    }
    if (output > 0) {
      console.log("1");
    } else {
      console.log("2");
    }
  }
};

main();

"use strict";
var input = '';
var inputResolve;
var inputPromise = new Promise(resolve => inputResolve = resolve);
process.stdin.on('data', c => input += c);
process.stdin.on('end', () => {
    inputResolve();
});
(async () => {
    // var time = Date.now();
    await inputPromise;
    var inputs = input.split(/\r?\n/);
    var t = +inputs[0];
    for (let i = 0; i < t; i++) {
        var n = +inputs[i * 2 + 1];
        var number = inputs[i * 2 + 2];
        if (n == 1) {
            console.log(number % 2 == 0 ? 2 : 1);
            continue;
        }
        if (n % 2 == 1) {
            console.log([...number].some((v, i) => i % 2 == 0 && v % 2 == 1) ? 1 : 2);
        }
        else {
            console.log([...number].some((v, i) => i % 2 == 1 && v % 2 == 0) ? 2 : 1);
        }
    }
})();
Object.defineProperty(Object.prototype, '$k', {
    value: function () { return Object.keys(this); }
});
Object.defineProperty(Object.prototype, '$v', {
    value: function () { return Object.values(this); }
});
Object.defineProperty(Object.prototype, '$kv', {
    value: function () { return Object.entries(this); }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0); };
Array.prototype.uniq = function (fn) {
    var set = new Set();
    return this.filter(v => {
        var newValue = !set.has(fn ? fn(v) : v);
        set.add(fn ? fn(v) : v);
        return newValue;
    });
};
Array.prototype.toObj = function (fn) {
    return this.map(v => fn(v)).reduce((p, v) => {
        p[v[0]] = v[1];
        return p;
    }, {});
};

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

    A();
});

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

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

    return a;
}

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

function A(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let n = pi(readline());
        let s = ti(readline().split(''));

        let isEvenEven = false;
        let isOddOdd = false;
        for(let i = 0; i < n; i++){
            if((i+1) % 2 === 0){
                if(!isEvenEven){
                    isEvenEven = s[i] % 2 === 0;
                }
            }else{
                if(!isOddOdd){
                    isOddOdd = s[i] % 2 !== 0;
                }
            }
        }

        if(n % 2 === 0){
            if(isEvenEven)
                console.log(2);
            else{
                console.log(1);
            }
        }else{
            if(isOddOdd)
                console.log(1);
            else{
                console.log(2);
            }
        }
    }
}

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

const digiGame = (n, _d) => {
  const arr = _d.toString(10).split("").map(Number);
  let output = 0;
  if (n % 2 === 0) {
    for (let evenIndex = 0; evenIndex < n / 2; evenIndex++) {
      if (arr[2 * evenIndex + 1] % 2 === 0) output++;
    }
    if (output > 0) {
      console.log("2");
    } else {
      console.log("1");
    }
  } else {
    output = 0;
    for (let oddIndex = 0; oddIndex < (n + 1) / 2; oddIndex++) {
      if (arr[(2 * oddIndex) % 2 === 0]) output++;
    }
    if (output > 0) {
      console.log("1");
    } else {
      console.log("2");
    }
  }
};

readline.question("", (t) => {
  for (let i = 1; i <= t; i++) {

      readline.question("", (n) => {
        readline.question("", (_d) => {
            digiGame(n, _d);
        });
      });
  }

});

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 main() {
  let t = +readLine();
  while (t--) {
    const len = +readLine();
    const str = readLine();
    let win = false;

    if (len % 2 === 1) {
      for (let i = 0; i < len; i += 2) {
        if (+str[i] % 2 === 1) win = true;
        break;
      }
      if (win) console.log(1);
      else console.log(2);
    } else {
      for (let i = 1; i < len; i += 2) {
        if (+str[i] % 2 === 0) win = true;
        break;
      }
      if (win) console.log(2);
      else console.log(1);
    }
  }
}


You are given $$$n$$$ strings $$$s_1, s_2, \dots, s_n$$$ of length at most $$$\mathbf{8}$$$. For each string $$$s_i$$$, determine if there exist two strings $$$s_j$$$ and $$$s_k$$$ such that $$$s_i = s_j + s_k$$$. That is, $$$s_i$$$ is the concatenation of $$$s_j$$$ and $$$s_k$$$. Note that $$$j$$$ can be equal to $$$k$$$.Recall that the concatenation of strings $$$s$$$ and $$$t$$$ is $$$s + t = s_1 s_2 \dots s_p t_1 t_2 \dots t_q$$$, where $$$p$$$ and $$$q$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. For example, concatenation of "code" and "forces" is "codeforces".

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of strings. Then $$$n$$$ lines follow, the $$$i$$$-th of which contains non-empty string $$$s_i$$$ of length at most $$$\mathbf{8}$$$, consisting of lowercase English letters. Among the given $$$n$$$ strings, there may be equal (duplicates). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

For each test case, output a binary string of length $$$n$$$. The $$$i$$$-th bit should be $$$\texttt{1}$$$ if there exist two strings $$$s_j$$$ and $$$s_k$$$ where $$$s_i = s_j + s_k$$$, and $$$\texttt{0}$$$ otherwise. Note that $$$j$$$ can be equal to $$$k$$$.

3

5

abab

ab

abc

abacb

c

3

x

xx

xxx

8

codeforc

es

codes

cod

forc

forces

e

code

NoteIn the first test case, we have the following:   $$$s_1 = s_2 + s_2$$$, since $$$\texttt{abab} = \texttt{ab} + \texttt{ab}$$$. Remember that $$$j$$$ can be equal to $$$k$$$.  $$$s_2$$$ is not the concatenation of any two strings in the list.  $$$s_3 = s_2 + s_5$$$, since $$$\texttt{abc} = \texttt{ab} + \texttt{c}$$$.  $$$s_4$$$ is not the concatenation of any two strings in the list.  $$$s_5$$$ is not the concatenation of any two strings in the list.  Since only $$$s_1$$$ and $$$s_3$$$ satisfy the conditions, only the first and third bits in the answer should be $$$\texttt{1}$$$, so the answer is $$$\texttt{10100}$$$.

var t = parseInt(readline());

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

    var set = new Set();
    var arr = [];

    for (var j = 0; j < n; j++) {
        var str = readline();
        set.add(str);
        arr.push(str);
    }

    for (var j = 0; j < arr.length; j++) {
        for (var k = 1; k < arr[j].length; k++) {
            if (
                set.has(arr[j].substr(0, k)) &&
                set.has(arr[j].substr(k, arr[j].length))
            ) {
                arr[j] = 1;
                break;
            }
        }
        arr[j] = arr[j] === 1 ? 1: 0;
    }

    print(arr.join(''));
}

var t = +readline();

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

      var nums = [];
    var t1 = +readline();
    for(var k = 0; k < t1; k++){
      var t3 = readline();
      nums.push(t3);
    }
    print(DoubleString(nums));

}

function DoubleString(list){

   var set = new Set();

  for(var each of list){
    set.add(each);
  };

  var res = new Array(list.length).fill(0);

  for(var k = 0; k<list.length; k++){
    var word = list[k];
    for(var i = 0; i<word.length; i++){
      var l1 = word.slice(0,i);
      var l2 = word.slice(i);
      if (set.has(l1) && set.has(l2)) {
        res[k] = 1;
        break;
      }
    }

  }
  return res.join('');

}

var tests = parseInt(readline());
    for (var t=0; t<tests;t++) {
        var n = parseInt(readline());
        var set = new Set();
        var arr = [];
        for (var i =0; i < n; i++) {
            arr.push(readline());
            set.add(arr[i]);
        }
        var ans = [];
        for (var i=0;i<n;i++) {
            var s = arr[i];
            var b = 0;
            for (var j=1;j<s.length;j++) {
                if (set.has(s.substring(j)) && set.has(s.substring(0, j))) {
                    b = 1;
                    break;
                }
            }
            ans.push(b);
        }
        print(ans.join(''));
    }

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function 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 n = readline();
        let strings = new Array();
        let dict = {};
        let result = new Array(n).fill(0);
        for (let i = 0; i < n; i++) {
            let str = readline();
            strings.push(str);
            if (dict[str]) {
                dict[str] = 2;
            } else {
                dict[str] = 1;
            }
        }

        wordLoop: for (let i = 0; i < n; i++) {
            lengthLoop: for (let len = 1; len < strings[i].length; len++) {
                let word = strings[i].substring(0, len);
                let suffix = strings[i].substring(len);
                if (word.length === strings[i].length / 2 && dict[word] === 2 && word === suffix) {
                    result[i] = '1';
                    continue wordLoop;
                }
                if (dict[word] && dict[suffix]) {
                    result[i] = '1';
                    continue wordLoop;
                } else {
                    continue lengthLoop;
                }
            }
            result[i] = '0';
        }

        output(result.join(''));
    }
}

// // cat .\input.txt | node .\script.js
'use strict';
let data = ''; // raw
let inputs = ''; // iterator
function read() { return inputs.next().value.trim(); };

async function solve() {
    let n;
    n = parseInt(await read())
    let s = new Array(n)
    let mp = new Map()
    for (let i = 0; i < n; i++) {
        s[i] = await read()
        mp.set(s[i], true)
    }
    for (let i = 0; i < n; i++) {
        let ok = false
        for (let j = 1; j < s[i].length; j++) {
            let pref = s[i].substring(0, j)
            let suff = s[i].substring(j, s[i].length)
            if (mp.get(pref) && mp.get(suff)) { ok = true }
        }
        process.stdout.write(ok ? '1' : '0');
    }
    process.stdout.write('\n');
}

async function main() {
    let tt = parseInt(await read())
    for (let i = 0; i < tt; i++) { await solve() }
}

process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => data += input);
process.stdin.on('end', async () => {
    let splitted = data.split('\r\n')
    inputs = await splitted.values();
    main();
});

function Solution() {
  let t = 0;
  const N = Number(lines[t++]);
  const res = [];
  for (let i = 0; i < N; i++) {
    const n = Number(lines[t++]);

    const strArr = [];
    for (let j = 0; j < n; j++) {
      strArr.push(lines[t++]);
    }

    const set = new Set(strArr);
    const r = [];

    for (let j = 0; j < n; j++) {
      const curr = strArr[j];
      let flag = false;
      for (let z = 1; z < curr.length; z++) {
        if (set.has(curr.substring(0, z)) && set.has(curr.substring(z))) {
          flag = true;
          break;
        }
      }
      if (flag) r.push(1)
      else r.push(0);
    }

    res.push(r.join(''));
  }
  return res.join('\n');
}

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', () => {
  console.log(Solution());
});

const readline = require("readline");

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

let lineNum = 0;
let strCnt = 0;
let curCnt = 0;
/** @type {string[]} arr */
let arr = [];
let set = new Set();

rl.on("line", line => {
    let num = Number(line);
    if (lineNum === 0) {
        // skip
    } else if (!isNaN(num)) {
        strCnt = num;
        curCnt = 0;
        set.clear();
        arr = [];
    } else {
        curCnt++;
        set.add(line);
        arr.push(line);
        if (curCnt === strCnt) {
            let ans = [];
            for (let s of arr) {
                let matched = false;
                for (let i = 1; i < s.length; i++) {
                    if (set.has(s.substring(0, i)) && set.has(s.substring(i))) {
                        matched = true;
                        break;
                    }
                }

                ans.push(matched ? "1" : "0");
            }
            console.log(ans.join(""));
        }
    }

    lineNum++;
});

const readline = require("readline");

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

let lineNum = 0;
let strCnt = 0;
let curCnt = 0;
/** @type {string[]} arr */
let arr = [];
let set = new Set();

rl.on("line", line => {
    let num = Number(line);
    if (lineNum === 0) {
        // skip
    } else if (!isNaN(num)) {
        strCnt = num;
        curCnt = 0;
        set.clear();
        arr = [];
    } else {
        curCnt++;
        set.add(line);
        arr.push(line);
        if (curCnt === strCnt) {
            let ans = "";
            for (let s of arr) {
                let matched = false;
                for (let i = 1; i < s.length; i++) {
                    if (set.has(s.substring(0, i)) && set.has(s.substring(i))) {
                        matched = true;
                        break;
                    }
                }

                ans += matched ? "1" : "0";
            }
            console.log(ans);
        }
    }

    lineNum++;
});

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;
}
// console.log(input)
var T = readline();
// var inf = 1000000000000;
for(var tc=1;tc<=T;tc++) {
  var n = readline()//.split(' ').map((x) => parseInt(x));
  // var a = readline().split(' ').map((x) => parseInt(x));
  var mp = new Map();
  var ans = "";
  var s = []
  for(var i=0;i<n;i++) {
    var a = readline();
    mp.set(a, 0)
    s.push(a);
  }
  // if(tc==1)console.log(s)
//   if(tc==1) console.log(mp)
  for(var i=0;i<n;i++) {
    var ok = false;
    // if(tc==1)console.log(s[i])
    for(var j=0;j<s[i].length;j++) {
      var f = s[i].slice(0, j+1);
      var se = s[i].slice(j+1, s[i].length);
      // if(tc == 1) console.log([f,se,j]);
      if(mp.has(se) && mp.has(f)) {
        ans += 1;
        ok = true;
        break;
      }
    }
    if(!ok) ans += 0;
  }
  console.log(ans)
}

const readline = require('readline')

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

function solve(n, arr) {
    const map = arr.reduce((o, x) => {
        o[x] = 1
        return o
    }, {})
    const ans = arr.map(x => {
        for (let i = 1; i < x.length; i++) {
            const a = x.slice(0, i)
            const b = x.slice(i)
    // console.log(a, b)
            if (map[a] && map[b]) {
                return 1
            }
        }
        return 0
    })
    return ans.join('')
}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let n = parseInt(readline());
    let arr = [];
    for (let i = 0; i < n; i++) arr.push(readline().trim());
    let obj = {};
    if (n === 1) {
      console.log(0);
      continue;
    }
    for (let i = 0; i < n; i++) {
      obj[arr[i]] = 1;
    }
    let obj1 = {};
    let res = "";
    for (let i = 0; i < n; i++) {
      let flag = 0;
      if (arr[i].length > 1 && !obj1[arr[i]]) {
        let x = arr[i];
        for (let i = 1; i < x.length; i++) {
          if (obj[x.slice(0, i)] && obj[x.slice(i, x.length)]) {
            flag = 1;
            break;
          }
        }
        res += flag;
        if (flag === 0) obj1[arr[i]] = 1;
        else obj1[arr[i]] = 2;
      } else {
        if (arr[i].length === 1) res += flag;
        else {
          if (obj1[arr[i]] === 1) res += 0;
          else res += 1;
        }
      }
    }
    console.log(res);
  }
};
solve();

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var list = nextStrArray(N);
		var set = new Set(list);
		var output = new Array(N).fill("0");
		for(var i = 0; i < N; i++){
			var s = list[i];
			var ok = false;
			for(var j = 0; j < s.length - 1; j++){
				var L = s.substring(0, j + 1);
				var R = s.substring(j + 1);

				if(set.has(L) && set.has(R)){
					ok = true;
				}
				if(L == R && set.has(L)){
					ok = true;
				}
			}
			if(ok){
				output[i] = "1";
			}
		}
		myout(myconv(output, 0));
	}
}

var t = parseInt(readline());

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

    var set = new Set();
    var arr = [];

    for (var j = 0; j < n; j++) {
        var str = readline();
        set.add(str);
        arr.push(str);
    }

    for (var j = 0; j < arr.length; j++) {
        for (var k = 1; k < arr[j].length - 1; k++) {
            if (
                set.has(arr[j].substr(0, k)) &&
                set.has(arr[j].substr(k, arr[j].length))
            ) {
                arr[j] = 1;
                break;
            }
        }
        arr[j] = arr[j] === 1 ? 1: 0;
    }

    print(arr.join(''));
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function 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 n = readline();
        let strings = new Array();
        let dict = {};
        let result = new Array(n).fill(0);
        for (let i = 0; i < n; i++) {
            let str = readline();
            strings.push(str);
            if (dict[str]) {
                dict[str] = 2;
            } else {
                dict[str] = 1;
            }
        }

        wordLoop: for (let i = 0; i < n; i++) {
            lengthLoop: for (let len = 1; len < strings[i].length; len++) {
                let word = strings[i].substring(0, len);
                let suffix = strings[i].substring(len);
                if (word.length === strings[i].length / 2 && dict[word] === 2 && word === suffix) {
                    result[i] = '1';
                    continue wordLoop;
                }
                if (dict[word] === 1 && dict[suffix]) {
                    result[i] = '1';
                    continue wordLoop;
                } else {
                    continue lengthLoop;
                }
            }
            result[i] = '0';
        }

        output(result.join(''));
    }
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function 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 n = readline();
        let strings = new Array();
        let dict = {};
        let result = new Array(n).fill(0);
        for (let i = 0; i < n; i++) {
            let str = readline();
            strings.push(str);
            if (dict[str]) {
                dict[str] = 2;
            } else {
                dict[str] = 1;
            }
        }

        wordLoop: for (let i = 0; i < n; i++) {
            lengthLoop: for (let len = 1; len <= strings[i].length; len++) {
                let word = strings[i].substring(0, len);
                if (word.length === strings[i].length / 2 && dict[word] === 2) {
                    result[i] = '1';
                    continue wordLoop;
                }
                let suffix = strings[i].substring(len);
                if (dict[word] === 1 && dict[suffix]) {
                    result[i] = '1';
                    continue wordLoop;
                } else {
                    continue lengthLoop;
                }
            }
            result[i] = '0';
        }

        output(result.join(''));
    }
}

// // cat .\input.txt | node .\script.js
'use strict';
const util = require('util')
let data = ''; // raw
let inputs = ''; // iterator
function read() {
    let value = inputs.next().value.trim();
    return value
};
async function solve() {
    try {
        let n = parseInt(await read())
        let s = new Array(n)
        let mp = new Map()
        for (let i = 0; i < n; i++) {
            s[i] = await read()
            mp.set(s[i], true)
        }
        for (let i = 0; i < n; i++) {
            let ok = false
            for (let j = 1; j < s[i].length; j++) {
                let pref = s[i].substring(0, j)
                let suff = s[i].substring(j, s[i].length - j)
                if (mp.get(pref) && mp.get(suff)) {
                    ok = true
                }
            }
            process.stdout.write(ok == true ? '1' : '0');
        }
        process.stdout.write('\n');
    } catch (error) {
        console.log(error);
    }
}

async function main() {
    let tt = parseInt(await read())
    for (let i = 0; i < tt; i++) {
        await solve()
    }
}

process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => data += input);
process.stdin.on('end', async () => {
    let splitted = data.split('\r\n')
    inputs = await splitted.values();
    await main();
});

// https://stackoverflow.com/questions/20086849/how-to-read-from-stdin-line-by-line-in-node
// // cat .\input.txt | node .\script.js
'use strict';
const util = require('util')
let data = ''; // raw
let inputs = ''; // iterator
function read() {
    return inputs.next().value.trim();
};
async function main(read) {
    try {
        let tasks = parseInt(await read())
        let result = []
        for (let i = 0; i < tasks; i++) {
            const sub_length = parseInt(await read())
            result[i] = [new Array(sub_length).fill(0)]
            for (let j = 0; j < sub_length; j++) {
                const element = (await read());
                result[i] = [...result[i], element]
            }
        }
        for (let i = 0; i < result.length; i++) {
            const element_i = result[i];
            for (let j = 1; j < element_i.length; j++) {
                let element_j = element_i[j];
                // console.log(element_j)
                for (let k = 1; k < element_i.length; k++) {
                    if (j == k) continue
                    let element_k = element_i[k];
                    if (element_j.includes(element_k)) {
                        // console.log(element_j, ' << ', element_k)
                        element_j = element_j.replace(element_k, '')
                        --k
                    }
                    if (element_j.length == 0) result[i][0][j - 1] = 1
                }
            }
        }
        return result.map(e => e[0].join('')).join('\n')
    } catch (error) {
        console.log(error);
    }
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => data += input);
process.stdin.on('end', async () => {
    inputs = data.split('\n').values();
    const result = await main(read);
    // console.log(util.inspect(result, { showHidden: false, depth: null, colors: true }))
    // console.log(result)
    process.stdout.write(result);
});

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;
}
// console.log(input)
var T = readline();
// var inf = 1000000000000;
for(var tc=1;tc<=T;tc++) {
  var n = readline()//.split(' ').map((x) => parseInt(x));
  // var a = readline().split(' ').map((x) => parseInt(x));
  var mp = new Map();
  var ans = "";
  var s = []
  for(var i=0;i<n;i++) {
    var a = readline();
    mp.set(a, 0)
    s.push(a);
  }
  // if(tc==1)console.log(s)
  if(tc==1) console.log(mp)
  for(var i=0;i<n;i++) {
    var ok = false;
    // if(tc==1)console.log(s[i])
    for(var j=0;j<s[i].length;j++) {
      var f = s[i].slice(0, j+1);
      var se = s[i].slice(j+1, s[i].length);
      // if(tc == 1) console.log([f,se,j]);
      if(mp.has(se) && mp.has(f)) {
        ans += 1;
        ok = true;
        break;
      }
    }
    if(!ok) ans += 0;
  }
  console.log(ans)
}


In the beginning of the new year Keivan decided to reverse his name. He doesn't like palindromes, so he changed Naviek to Navick.He is too selfish, so for a given n he wants to obtain a string of n characters, each of which is either 'a', 'b' or 'c', with no palindromes of length 3 appearing in the string as a substring. For example, the strings "abc" and "abca" suit him, while the string "aba" doesn't. He also want the number of letters 'c' in his string to be as little as possible.

The first line contains single integer n (1 ≤ n ≤ 2·105) — the length of the string.

Print the string that satisfies all the constraints. If there are multiple answers, print any of them.

NoteA palindrome is a sequence of characters which reads the same backward and forward.

  var n = parseInt(readline());
  var res = [];
  for(var i = 0; i < n; i += 4) {
    res.push('a', 'a', 'b', 'b');
  }
  res.length = n;
  print(res.join(''));

var n = Number(readline());
var newStr = [];
for (var i = 0; i < n; i++){
    if(checkPalindrome('a', i))
        newStr[i] = 'b';
    else
        newStr[i] = 'a';
}

print(newStr.join(''));

function checkPalindrome(letter, size){
    if (size < 2)
        return false;

    return (letter == newStr[size - 2]);
}

  var n = parseInt(readline());
  var res = [];
  for(var i = 0; i < n; i += 5) {
    res.push('a', 'a', 'b', 'b');
  }
  res.length = n;
  print(res.join(''));

  var n = parseInt(readline());
  var res = [];
  for(var i = 0; i < n; i += 5) {
    res.push('a', 'a', 'b', 'b', 'c');
  }
  res.length = n;
  print(res.join(''));

  var n = parseInt(readline());
  var res = '';
  for(var i = 5; i < n; i += 5) {
    res += 'aabbc';
  }
  res += 'aabbc'.substr(0, (n - res.length));
  print(res);


Monocarp has got an array $$$a$$$ consisting of $$$n$$$ integers. Let's denote $$$k$$$ as the mathematic mean of these elements (note that it's possible that $$$k$$$ is not an integer). The mathematic mean of an array of $$$n$$$ elements is the sum of elements divided by the number of these elements (i. e. sum divided by $$$n$$$).Monocarp wants to delete exactly two elements from $$$a$$$ so that the mathematic mean of the remaining $$$(n - 2)$$$ elements is still equal to $$$k$$$.Your task is to calculate the number of pairs of positions $$$[i, j]$$$ ($$$i < j$$$) such that if the elements on these positions are deleted, the mathematic mean of $$$(n - 2)$$$ remaining elements is equal to $$$k$$$ (that is, it is equal to the mathematic mean of $$$n$$$ elements of the original array $$$a$$$).

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of elements in the array. The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^{9}$$$), where $$$a_i$$$ is the $$$i$$$-th element of the array. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

Print one integer — the number of pairs of positions $$$[i, j]$$$ ($$$i < j$$$) such that if the elements on these positions are deleted, the mathematic mean of $$$(n - 2)$$$ remaining elements is equal to $$$k$$$ (that is, it is equal to the mathematic mean of $$$n$$$ elements of the original array $$$a$$$).

NoteIn the first example, any pair of elements can be removed since all of them are equal.In the second example, there is no way to delete two elements so the mathematic mean doesn't change.In the third example, it is possible to delete the elements on positions $$$1$$$ and $$$3$$$, or the elements on positions $$$4$$$ and $$$5$$$.

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let n = BigInt(readline());
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => BigInt(cur));
    let sum = 0n;
    for (let i = 0; i < n; i++) sum += arr[i];
    let t = sum * (n - 2n);
    if (t % n) console.log(0);
    else {
      t = t / n;
      let p = sum - t;
      let obj = {};
      for (let i = 0; i < n; i++) {
        if (!obj[arr[i]]) obj[arr[i]] = 1n;
        else obj[arr[i]]++;
      }
      let cnt = 0n;
      if (n - 2n === 1n) {
        if (obj[t]) console.log(obj[t] + "");
        else console.log(0);
        continue;
      }
      for (let i = 0; i < n; i++) {
        obj[arr[i]]--;
        let k = p - arr[i];
        if (obj[k]) cnt += obj[k];
      }
      console.log(cnt + "");
    }
  }
};
solve();

// dist/FinalCode/Algo/binarySearch.js
var binSearch = function(arrayData, data, customLowIdx, customHighIdx) {
  var low = customLowIdx;
  var high = customHighIdx;
  var mid;
  while (high - low > 10) {
    mid = Math.floor((high - low) / 2 + low);
    if (data <= arrayData[mid]) {
      high = mid;
    } else {
      low = mid;
    }
  }
  for (var idx = low; idx <= high; idx++) {
    if (arrayData[idx] === data) {
      return idx;
    }
  }
  return -1;
};

// dist/FinalCode/Common/InputOutputClass.js
var Input = function() {
  function Input2(inputData) {
    var _this = this;
    this.SettleStream = function() {
      var re = /\s+/;
      _this.inputWords = _this.inputStream.split(re);
      _this.inputWordsLength = _this.inputWords.length;
    };
    this.getLength = function() {
      return _this.inputWordsLength;
    };
    this.getEveryWord = function() {
      return _this.inputWords;
    };
    this.getNextWord = function() {
      _this.inputWordsCount++;
      if (_this.inputWordsLength < _this.inputWordsCount) {
        return "";
      }
      return _this.inputWords[_this.inputWordsCount - 1];
    };
    this.getNextString = function() {
      return _this.getNextWord();
    };
    this.getNextBigInt = function() {
      return BigInt(_this.getNextWord());
    };
    this.getNextNumber = function() {
      return Number(_this.getNextWord());
    };
    this.getNextInt = function() {
      return parseInt(_this.getNextWord(), 10);
    };
    this.getNextFloat = function() {
      return parseFloat(_this.getNextWord());
    };
    this.inputWordsCount = 0;
    this.inputStream = inputData;
  }
  Input2.prototype.SetStream = function(chunk) {
    this.inputStream += chunk;
  };
  Input2.prototype.getNextIntArray = function(elementCount) {
    var resultArray = new Array(elementCount);
    for (var idx = 0; idx < elementCount; idx++) {
      resultArray[idx] = this.getNextInt();
    }
    return resultArray;
  };
  return Input2;
}();
var InputOutputClass_default = Input;
var writeLine = function(outputElement) {
  var _internalWrite = function(_internalOutputElement) {
    process.stdout.write(_internalOutputElement);
  };
  _internalWrite(String(outputElement) + "\n");
};

// dist/main.js
var rw = new InputOutputClass_default("");
process.stdin.resume();
process.stdin.setEncoding("utf-8");
process.stdin.on("data", function(chunk) {
  rw.SetStream(chunk);
});
process.stdin.on("end", function() {
  rw.SettleStream();
  mainFunc();
});
var mainFunc = function() {
  testCases();
};
var testCases = function() {
  var test = rw.getNextInt();
  for (var i = 0; i < test; i++) {
    solveCase();
  }
};
var solveCase = function() {
  var n = rw.getNextInt();
  var nums = rw.getNextIntArray(n);
  var sum = 0;
  for (var i = 0; i < n; i++) {
    sum += nums[i];
  }
  var avg = sum / n;
  nums.sort(function(a, b2) {
    return a - b2;
  });
  var answer = 0;
  var j = n - 1;
  for (var i = 0; i < n - 1; i++) {
    while (nums[i] + nums[j] > 2 * avg && i < j) {
      j--;
    }
    if (!(i < j)) {
      break;
    }
    if (nums[i] + nums[j] === 2 * avg) {
      var b = binSearch(nums, nums[j], i + 1, n - 1);
      if (b !== -1) {
        answer += j - b + 1;
      }
    }
  }
  writeLine("" + answer);
};

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

let ls = [];

function solve(){
    let l = 0;
    const t = parseInt(ls[l++]);
    for (let u = 0; u < t; u++){
        const n = parseInt(ls[l++]);
        const a = ls[l++].split(' ').map(i => parseInt(i));
        const cnt = {};
        let sum = 0;
        for (let i = 0; i < n; i++){
            if (cnt[a[i]]){
                cnt[a[i]]++;
            }
            else{
                cnt[a[i]] = 1;
            }
            sum += a[i];
        }

        const pairSum = 2*sum/n;
        if (!Number.isInteger(pairSum)){
            console.log('0');
            continue;
        }

        let ans = 0;
        for (let i = 0; i < n; i++){
            let b = pairSum - a[i];
            let c = 0;
            if (cnt[b]){
                c = cnt[b];
            }
            if (a[i] == b){
                c = Math.max(0, c - 1);
            }
            ans += c;
        }
        console.log(ans/2);
    }
}

rl.on('line', (l) => ls.push(l));
rl.on('close', () => solve());

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

const readLine = () => dataitr.next().value.trim();
function rl () {
	let ans = readLine().split(' ');
	if (!isNaN(Number(ans[0]))) ans = ans.map(x => Number(x));
	return ans.length == 1 ? ans[0] : ans;
}
const rla = () => readLine().split(' ').map(x => Number(x));

function main () {
	let t = rl();
	while (t--) {
		let n = rl();
		let a = rla();

		a.sort((x, y) => x - y);
		let sum = 0;
		for (x of a) sum += x;
		let m = sum / n;

		let i = 0; j = n - 1, ans = 0;;
		while (i < j) {
			if (a[i] + a[j] == 2 * m) {
				if (a[i] == a[j]) {
					elms = j - i + 1;
					ans += elms * (elms - 1) / 2;
					break;
				}
				let i0 = i, j0 = j;
				i++;
				while (a[i] == a[i-1]) i++;
				j--;
				while (a[j] == a[j+1]) j--;
				ans += (i - i0) * (j0 - j);
			}
			else if (a[i] + a[j] < 2 * m) i++;
			else j--;
			//console.log(i,j, a[i] + a[j] , 2 * m);
		}
		console.log(ans);
	}
}

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var list = nextIntArray(N);
		var map = getCountMap(list);
		var sum = 0;
		for(var i = 0; i < N; i++){
			sum += list[i];
		}
		var avg = sum / N;
		var output = 0;
		var ato = 0;
		var keys = Object.keys(map);
		for(var i = 0; i < keys.length; i++){
			var V = map[keys[i]];
			var L = (avg * 2) - keys[i];
			if(L == keys[i]){
				ato = V * (V - 1) / 2;
			}else if(map[L] != null){
				output += map[keys[i]] * map[L];
			}
		}
		myout(output / 2 + ato);
	}
}

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'))
// })()
})

function solve(n, arr) {
    const sum = arr.reduce((s, x) => s + x, 0)
    const target = sum * 2 / n
    // console.log(sum, n, target)
    arr.sort((a, b) => a - b)

    let ans = 0
    for (let i = 0; i < arr.length; i++) {
        const a1 = binarySearch(i + 1, n - 1, x => arr[x] < target - arr[i])
        const a2 = binarySearch(i + 1, n - 1, x => arr[x] <= target - arr[i])
    // console.log(a1, a2)
        ans += a2 - a1
    }
    // console.log('-')
    return ans
}
function binarySearch(l, r, fn) {
    while (l <= r) {
        const m = Math.floor((l + r) / 2)
        if (fn(m)) {
            l = m + 1
        } else {
            r = m - 1
        }
    }
    return r
}

var t = parseInt(readline());
  function solve() {
    var n = parseInt(readline());
    var inp = readline()
      .split(" ")
      .map((data) => +data);
    var tot = inp.reduce((p, c) => {
        p += c;
        return p;
    }, 0);
    var rem = 2 * (tot / n);
    var map = {};
    for(var i1 = 0;i1 < n;i1++) {
        if(map[inp[i1]]) {
            map[inp[i1]] += 1;
        }
        else {
            map[inp[i1]] = 1;
        }
    }
    var ans = 0;
    for(var i = 0;i < n;i++) {
        var other = rem - inp[i];
        if(map[other]) {
            var f1 = map[other];
            var f2 = map[inp[i]];

            if(other == inp[i]) {
                if(f1 > 1) {
                    ans += (f1 * (f1 - 1)) / 2;
                    map[other] = 0;
                }
                else {
                    map[other] = 0;
                }
            }
            else {
                ans += (f1 * f2);
                map[inp[i]] = 0;
                map[other] = 0;
            }
        }
    }
    return ans;
  }

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

var t = parseInt(readline());
  function solve() {
    var n = parseInt(readline());
    var inp = readline()
      .split(" ")
      .map((data) => +data);
    var sum = 0;
    var mp = {};
    for (var i = 0; i < n; i++) {
      sum += inp[i];
      if (mp.hasOwnProperty(inp[i])) {
        mp[inp[i]]++;
      } else {
        mp[inp[i]] = 1;
      }
    }
    var ans = 0;
    var need = (2 * sum) / n;
    if ((2 * sum) % n !== 0) {
      return 0;
    }
    for (var i = 0; i < n; i++) {
      var req = need - inp[i];
      var val = mp[req] || 0;
      ans += val;
      if (inp[i] == req) ans -= 1;
    }
    return ans / 2;
  }

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

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let n = parseInt(readline());
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let sum = 0;
    for (let i = 0; i < n; i++) sum += arr[i];
    let t = (sum * (n - 2)) / n;
    if (t % 1 !== 0) console.log(0);
    else {
      let p = sum - t;
      let obj = {};
      for (let i = 0; i < n; i++) {
        if (!obj[arr[i]]) obj[arr[i]] = 1;
        else obj[arr[i]]++;
      }
      let cnt = 0;
      if (n - 2 === 1) {
        if (obj[t]) console.log(obj[t]);
        else console.log(0);
        continue;
      }
      for (let i = 0; i < n; i++) {
        obj[arr[i]]--;
        let k = p - arr[i];
        if (obj[k]) cnt += obj[k];
      }
      console.log(cnt);
    }
  }
};
solve();

// dist/FinalCode/Algo/binarySearch.js
var binSearch = function(arrayData, data, customLowIdx, customHighIdx) {
  var low = customLowIdx;
  var high = customHighIdx;
  var mid;
  while (high - low > 10) {
    mid = Math.floor((high - low) / 2 + low);
    if (data <= arrayData[mid]) {
      high = mid;
    } else {
      low = mid;
    }
  }
  for (var idx = low; idx <= high; idx++) {
    if (arrayData[idx] === data) {
      return idx;
    }
  }
  return -1;
};

// dist/FinalCode/Common/InputOutputClass.js
var Input = function() {
  function Input2(inputData) {
    var _this = this;
    this.SettleStream = function() {
      var re = /\s+/;
      _this.inputWords = _this.inputStream.split(re);
      _this.inputWordsLength = _this.inputWords.length;
    };
    this.getLength = function() {
      return _this.inputWordsLength;
    };
    this.getEveryWord = function() {
      return _this.inputWords;
    };
    this.getNextWord = function() {
      _this.inputWordsCount++;
      if (_this.inputWordsLength < _this.inputWordsCount) {
        return "";
      }
      return _this.inputWords[_this.inputWordsCount - 1];
    };
    this.getNextString = function() {
      return _this.getNextWord();
    };
    this.getNextBigInt = function() {
      return BigInt(_this.getNextWord());
    };
    this.getNextNumber = function() {
      return Number(_this.getNextWord());
    };
    this.getNextInt = function() {
      return parseInt(_this.getNextWord(), 10);
    };
    this.getNextFloat = function() {
      return parseFloat(_this.getNextWord());
    };
    this.inputWordsCount = 0;
    this.inputStream = inputData;
  }
  Input2.prototype.SetStream = function(chunk) {
    this.inputStream += chunk;
  };
  Input2.prototype.getNextIntArray = function(elementCount) {
    var resultArray = new Array(elementCount);
    for (var idx = 0; idx < elementCount; idx++) {
      resultArray[idx] = this.getNextInt();
    }
    return resultArray;
  };
  return Input2;
}();
var InputOutputClass_default = Input;
var writeLine = function(outputElement) {
  var _internalWrite = function(_internalOutputElement) {
    process.stdout.write(_internalOutputElement);
  };
  _internalWrite(String(outputElement) + "\n");
};

// dist/main.js
var rw = new InputOutputClass_default("");
process.stdin.resume();
process.stdin.setEncoding("utf-8");
process.stdin.on("data", function(chunk) {
  rw.SetStream(chunk);
});
process.stdin.on("end", function() {
  rw.SettleStream();
  mainFunc();
});
var mainFunc = function() {
  testCases();
};
var testCases = function() {
  var test = rw.getNextInt();
  for (var i = 0; i < test; i++) {
    solveCase();
  }
};
var solveCase = function() {
  var n = rw.getNextInt();
  var nums = rw.getNextIntArray(n);
  var sum = 0;
  for (var i = 0; i < n; i++) {
    sum += nums[i];
  }
  var avg = sum / n;
  nums.sort(function(a, b2) {
    return a - b2;
  });
  var answer = 0;
  var j = n - 1;
  for (var i = 0; i < n - 1; i++) {
    while (nums[i] + nums[j] !== 2 * avg && i < j) {
      j--;
    }
    if (!(i < j)) {
      break;
    }
    var b = binSearch(nums, nums[j], i + 1, n - 1);
    answer += j - b + 1;
  }
  writeLine(answer);
};

var t = parseInt(readline());
  function solve() {
    var n = parseInt(readline());
    var inp = readline()
      .split(" ")
      .map((data) => +data);
    var tot = inp.reduce((p, c) => {
        p += c;
        return p;
    }, 0);
    var rem = 2 * (tot / n);
    var map = {};
    for(var i1 = 0;i1 < n;i1++) {
        if(map[inp[i1]]) {
            map[inp[i1]] += 1;
        }
        else {
            map[inp[i1]] = 1;
        }
    }
    var ans = 0;
    for(var i = 0;i < n;i++) {
        var other = rem - inp[i];
        if(map[other]) {
            var f1 = map[other];
            var f2 = map[inp[i]];

            if(other == inp[i]) {
                if(f1 > 1) {
                    ans += (f1 * (f1 - 1)) / 2;
                }
                else {
                    delete map[other]
                }
            }
            else {
                ans += (f1 * f2);
                map[inp[i]] = 0;
                map[other] = 0;
                delete map[other];
                delete map[inp[i]];
            }
        }
    }
    return ans;
  }

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

var t = parseInt(readline());
  function solve() {
    var n = parseInt(readline());
    var inp = readline()
      .split(" ")
      .map((data) => +data);
    var tot = inp.reduce((p, c) => {
        p += c;
        return p;
    }, 0);
    var rem = 2 * (tot / n);
    var map = {};
    for(var i1 = 0;i1 < n;i1++) {
        if(map[inp[i1]]) {
            map[inp[i1]] += 1;
        }
        else {
            map[inp[i1]] = 1;
        }
    }
    var ans = 0;
    for(var i = 0;i < n;i++) {
        var other = rem - inp[i];
        if(map[other]) {
            var f1 = map[other];
            var f2 = map[inp[i]];

            if(other == inp[i]) {
                if(f1 > 1) {
                    ans += (f1 * (f1 - 1)) / 2;
                }
                else {
                    map[other] = 0;
                }
            }
            else {
                ans += (f1 * f2);
                map[inp[i]] = 0;
                map[other] = 0;
            }
        }
    }
    return ans;
  }

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

var t = parseInt(readline());
  function solve() {
    var n = parseInt(readline());
    var inp = readline()
      .split(" ")
      .map((data) => +data);
    var tot = inp.reduce((p, c) => {
        p += c;
        return p;
    }, 0);
    var rem = (tot - ((tot / n) * (n - 2)));
    inp.sort((a, b) => a - b);
    var i = 0, j = n - 1;
    var ans = 0;
    while(i < j) {
        if(inp[i] + inp[j] > rem) {
            j -= 1;
        }
        else if(inp[i] + inp[j] < rem) {
            i += 1;
        }
        else {
            var cnti = 1;
            var cntj = 1;
            i = i + 1;
            j = j - 1;
            while(i < j && inp[i] == inp[i - 1]) {
                i += 1;
                cnti += 1;
            }
            while(i < j && inp[j] == inp[j + 1]) {
                j -= 1;
                cntj += 1;
            }
            ans += (cnti * cntj);
        }
    }
    return ans;
  }

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

var t = parseInt(readline());
  function solve() {
    var n = parseInt(readline());
    var inp = readline()
      .split(" ")
      .map((data) => +data);
    var tot = inp.reduce((p, c) => {
        p += c;
        return p;
    }, 0);
    var rem = (tot - ((tot / n) * (n - 2)));
    inp.sort((a, b) => a - b);
    // var i = 0, j = 0;
    // var ans = 0;
    // while(i < j) {
    //     if(inp[i] + inp[j] > rem) {
    //         j -= 1;
    //     }
    //     else if(inp[i] + inp[j] < rem) {
    //         i += 1;
    //     }
    //     else {
    //         var cnti = 1;
    //         var cntj = 1;
    //         var i1 = i + 1;
    //         var j1 = j - 1;
    //         while(i1 < j && inp[i1] == inp[i1 - 1]) {
    //             cnti += 1;
    //         }
    //         while(i < j1 && inp[j1] == inp[j1 + 1]) {
    //             cntj += 1;
    //         }
    //         ans += (cnti * cntj);
    //     }
    // }
    return rem;
  }

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

var t = parseInt(readline());
  function solve() {
    var n = parseInt(readline());
    var inp = readline()
      .split(" ")
      .map((data) => +data);
    var tot = inp.reduce((p, c) => {
        p += c;
        return p;
    }, 0);
    var rem = (tot - ((tot / n) * (n - 2)));
    inp.sort((a, b) => a - b);
    var i = 0, j = 0;
    var ans = 0;
    while(i < j) {
        if(inp[i] + inp[j] > rem) {
            j -= 1;
        }
        else if(inp[i] + inp[j] < rem) {
            i += 1;
        }
        else {
            var cnti = 1;
            var cntj = 1;
            var i1 = i + 1;
            var j1 = j - 1;
            while(i1 < j && inp[i1] == inp[i1 - 1]) {
                cnti += 1;
            }
            while(i < j1 && inp[j1] == inp[j1 + 1]) {
                cntj += 1;
            }
            ans += (cnti * cntj);
        }
    }
    return ans;
  }

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

var t = parseInt(readline());
  function solve() {
    var n = parseInt(readline());
    var inp = readline()
      .split(" ")
      .map((data) => +data);
    var sum = 0;
    var mp = {};
    for (var i = 0; i < n; i++) {
      sum += inp[i];
      if (mp.hasOwnProperty(inp[i])) {
        mp[inp[i]]++;
      } else {
        mp[inp[i]] = 1;
      }
    }
    var ans = 0;
    var need = (2 * sum) / n;
    if ((2 * sum) % n != 0) {
      return 0;
    }
    for (var i = 0; i < n; i++) {
      var req = need - inp[i];
      ans += mp[req];
      if (inp[i] == req) ans -= 1;
    }
    return ans / 2;
  }

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