You are given two strings $$$s$$$ and $$$t$$$ consisting of lowercase Latin letters. Also you have a string $$$z$$$ which is initially empty. You want string $$$z$$$ to be equal to string $$$t$$$. You can perform the following operation to achieve this: append any subsequence of $$$s$$$ at the end of string $$$z$$$. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if $$$z = ac$$$, $$$s = abcde$$$, you may turn $$$z$$$ into following strings in one operation:   $$$z = acace$$$ (if we choose subsequence $$$ace$$$);  $$$z = acbcd$$$ (if we choose subsequence $$$bcd$$$);  $$$z = acbce$$$ (if we choose subsequence $$$bce$$$). Note that after this operation string $$$s$$$ doesn't change.Calculate the minimum number of such operations to turn string $$$z$$$ into string $$$t$$$.

The first line contains the integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of test cases. The first line of each testcase contains one string $$$s$$$ ($$$1 \le |s| \le 10^5$$$) consisting of lowercase Latin letters. The second line of each testcase contains one string $$$t$$$ ($$$1 \le |t| \le 10^5$$$) consisting of lowercase Latin letters. It is guaranteed that the total length of all strings $$$s$$$ and $$$t$$$ in the input does not exceed $$$2 \cdot 10^5$$$.

For each testcase, print one integer — the minimum number of operations to turn string $$$z$$$ into string $$$t$$$. If it's impossible print $$$-1$$$.

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, ''))
  main(arr)
})

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

function sort(a, inc = true) {
  if(inc) a.sort((a, b) => a - b)
  else a.sort((a, b) => b - a)
}

function readInt(a, i) {
  if(i === undefined) return parseInt(a.shift())
  else return parseInt(a[i])
}

function readInts(a, i) {
  if(i === undefined) return arr.shift().split(' ').map(a => parseInt(a))
  else return arr[i].split(' ').map(a => parseInt(a))
}

function main(input) {
  let i = 0

  T=+input[0];
  for (x=0;x<T;x++){
          s=input[x*2+1]
          t=input[x*2+2]
          n=s.length
          dp=new Array(n+1)
          for (i=0;i<=n;i++)
            dp[i]=new Array(26)
          for (i=0;i<26;i++)
            dp[n][i]=-1

          for (i=s.length-1;i>=0;i--){
              for (j=0;j<26;j++)
                dp[i][j]=dp[i+1][j]
              dp[i][s.charCodeAt(i)-'a'.charCodeAt(0)]=i
          }
        ans=1
        pos=0
        for (i=0;i<t.length;i++){
            w=dp[pos][t.charCodeAt(i)-'a'.charCodeAt(0)]
            if (w==-1){
                ++ans
                pos=dp[0][t.charCodeAt(i)-'a'.charCodeAt(0)]+1
                if (pos==0){
                    ans=-1000000
                    break
                }
            } else {
                pos=w+1
            }
        }
        if (ans==-1000000)
            ans=-1
        wr(ans)
  }

}

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

let input = ''
let ptr = 0
process.stdin.on('data', (i) => {
  input += i
})

process.stdin.on('end', () => {
  input = input.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  main()
})

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

function sort(a, inc = true) {
  if(inc) a.sort((a, b) => a - b)
  else a.sort((a, b) => b - a)
}

function readInt() {
  return parseInt(input[ptr++])
}

function readString() {
  return input[ptr++]
}

function readStrings() {
  return input[ptr++].split(' ')
}

function readInts() {
  return input[ptr++].split(' ').map(a => parseInt(a))
}

function main() {
  let t  = readInt()
  while(t--) {
    const s = readString()
    const t = readString()
    let map = {}
    const sL = s.length
    const tL = t.length
    for(let i = 0; i < sL; i++) {
      if(!map[s[i]]) map[s[i]] = [i]
      else map[s[i]].push(i)
    }
    let curr = -1
    let count = 1
    let f = true
    for(let i = 0; i < tL; i++) {
      if(!map[t[i]]) {
        f = false
        break
      }
      // wr('curr', t[i], curr)
      let x = findMe(map[t[i]], curr)
      // wr('x', x, map[t[i]])
      if(x !== -1) curr = x
      else {
        count++
        curr = map[t[i]][0]
      }
    }
    if(!f) wr(-1)
    else wr(count)
  }

  function findMe(a, n) {
    let i = 0, j = a.length - 1
    while(i < j) {
      let m = Math.floor((i + j) / 2)
      // wr(i, m, j)
      if(a[m] <= n) {
        i = m + 1
      }
      else if(a[m] > n) {
        j = m
      }
    }
    if(a[i] > n) return a[i]
    else return -1
  }
}

'use strict';

function obtain(s, t) {
  const m = s.length;
  const n = t.length;

  const next = Array(m+1);
  next[m] = {};
  for (let i = s.length-1; i >= 0; i--) {
    next[i] = Object.assign({}, next[i+1]);
    next[i][s[i]] = i;
  }

  let res = 1;
  let i = 0, j = 0;
  while (j < n) {
    if (i >= m) {
      i = 0;
      res++;
    }
    if (next[i][t[j]] === undefined) {
      i = 0;
      if (next[i][t[j]] === undefined) {
        return -1;
      }
      res++;
    }
    i = next[i][t[j]] + 1;
    j++;
  }

  return res;
}

function main() {
  const t = Number(readline());
  for (let i = 0; i < t; i++) {
    const s = readline();
    const t = readline();
    const res = obtain(s, t);
    print(res);
  }
}

main();

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, ''))
  main(arr)
})

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

function sort(a, inc = true) {
  if(inc) a.sort((a, b) => a - b)
  else a.sort((a, b) => b - a)
}

function readInt(a, i) {
  if(i === undefined) return parseInt(a.shift())
  else return parseInt(a[i])
}

function readInts(a, i) {
  if(i === undefined) return arr.shift().split(' ').map(a => parseInt(a))
  else return arr[i].split(' ').map(a => parseInt(a))
}

function main(input) {
  let i = 0

  T=+input[0];
  for (x=0;x<T;x++){
          s=input[x*2+1]
          t=input[x*2+2]
          n=s.length
          dp=new Array(n+1)
          for (i=0;i<=n;i++)
            dp[i]=new Array(26)
          for (i=0;i<26;i++)
            dp[n][i]=-1

          for (i=s.length-1;i>=0;i--){
              for (j=0;j<26;j++)
                dp[i][j]=dp[i+1][j]
              dp[i][s.charCodeAt(i)-'a'.charCodeAt(0)]=i
          }
        ans=1
        pos=0
        for (i=0;i<t.length;i++){
            w=dp[pos][t.charCodeAt(i)-'a'.charCodeAt(0)]
            if (w==-1){
                ++ans
                pos=dp[0][t.charCodeAt(i)-'a'.charCodeAt(0)]+1
                if (pos==0){
                    ans=-1000000
                }
            } else {
                pos=w+1
            }
        }
        if (ans==-1000000)
            ans=-1
        wr(ans)
  }

}


Monocarp plays a computer game. There are $$$n$$$ different sets of armor and $$$m$$$ different weapons in this game. If a character equips the $$$i$$$-th set of armor and wields the $$$j$$$-th weapon, their power is usually equal to $$$i + j$$$; but some combinations of armor and weapons synergize well. Formally, there is a list of $$$q$$$ ordered pairs, and if the pair $$$(i, j)$$$ belongs to this list, the power of the character equipped with the $$$i$$$-th set of armor and wielding the $$$j$$$-th weapon is not $$$i + j$$$, but $$$i + j + 1$$$.Initially, Monocarp's character has got only the $$$1$$$-st armor set and the $$$1$$$-st weapon. Monocarp can obtain a new weapon or a new set of armor in one hour. If he wants to obtain the $$$k$$$-th armor set or the $$$k$$$-th weapon, he must possess a combination of an armor set and a weapon that gets his power to $$$k$$$ or greater. Of course, after Monocarp obtains a weapon or an armor set, he can use it to obtain new armor sets or weapons, but he can go with any of the older armor sets and/or weapons as well.Monocarp wants to obtain the $$$n$$$-th armor set and the $$$m$$$-th weapon. What is the minimum number of hours he has to spend on it?

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 2 \cdot 10^5$$$) — the number of armor sets and the number of weapons, respectively. The second line contains one integer $$$q$$$ ($$$0 \le q \le \min(2 \cdot 10^5, nm)$$$) — the number of combinations that synergize well. Then $$$q$$$ lines follow, the $$$i$$$-th line contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i \le n$$$; $$$1 \le b_i \le m$$$) meaning that the $$$a_i$$$-th armor set synergizes well with the $$$b_i$$$-th weapon. All pairs $$$(a_i, b_i)$$$ are distinct.

Print one integer — the minimum number of hours Monocarp has to spend to obtain both the $$$n$$$-th armor set and the $$$m$$$-th weapon.

NoteIn the first example, Monocarp can obtain the strongest armor set and the strongest weapon as follows:  Obtain the $$$2$$$-nd weapon using the $$$1$$$-st armor set and the $$$1$$$-st weapon;  Obtain the $$$3$$$-rd armor set using the $$$1$$$-st armor set and the $$$2$$$-nd weapon;  Obtain the $$$4$$$-th weapon using the $$$3$$$-rd armor set and the $$$2$$$-nd weapon. In the second example, Monocarp can obtain the strongest armor set and the strongest weapon as follows:  Obtain the $$$3$$$-rd armor set using the $$$1$$$-st armor set and the $$$1$$$-st weapon (they synergize well, so Monocarp's power is not $$$2$$$ but $$$3$$$);  Obtain the $$$4$$$-th weapon using the $$$3$$$-rd armor set and the $$$1$$$-st weapon.

const { reverse } = require('dns');
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 = 1//+lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const [n, m] = lines[l++].trim().split(' ').map(Number)
        const q = +lines[l++]
        const qs = lines.slice(l, l + q).map(str => str.trim().split(' ').map(Number))
        l += q
        output[i] = solve(n, m, q, qs)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, m, _, qs) {
    const map = qs.reduce((o, [a, b]) => {
        o[key(a, b)] = 1
        return o
    }, {})

    let q = [[1, 1, 0]]
    let nq
    let sb = 10
    // while (sb--) {
    while (1) {
        nq = []
        for (let i = 0; i < q.length; i++) {
            const [a, b, d] = q[i];
            const power = map[key(a, b)] ? a + b + 1 : a + b
            add(nq, n, m, [power, b, d + 1])
            add(nq, n, m, [a, power, d + 1])
        }
        nq.sort((a, b) => {
            if (a[0] === b[0]) {
                return b[1] - a[1]
            } else {
                return b[0] - a[0]
            }
        })
// console.log(nq)
        q = []
        let ma = 0
        let mb = 0
        for (let i = 0; i < nq.length; i++) {
            const [a, b, d] = nq[i];
            if (a >= n && b >= m) return d
            if (a <= ma && b <= mb) continue
            ma = Math.max(ma, a)
            mb = Math.max(mb, b)
            q.push([Math.min(n, a), Math.min(m, b), d])
        }
        if (!q.length) break
    }
    return -1
}
function add(q, n, m, [a, b, d]) {
    // if (a > n || b > m) return
    q.push([a, b, d])
}
function key(a, b) {
    return a + ',' + b
}

const { reverse } = require('dns');
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 = 1//+lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const [n, m] = lines[l++].trim().split(' ').map(Number)
        const q = +lines[l++]
        const qs = lines.slice(l, l + q).map(str => str.trim().split(' ').map(Number))
        l += q
        output[i] = solve(n, m, q, qs)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, m, _, qs) {
    const map = qs.reduce((o, [a, b]) => {
        o[key(a, b)] = 1
        return o
    }, {})

    let q = [[1, 1, 0]]
    let nq
    let sb = 10
    // while (sb--) {
    while (1) {
        nq = []
        for (let i = 0; i < q.length; i++) {
            const [a, b, d] = q[i];
            const power = map[key(a, b)] ? a + b + 1 : a + b
            nq.push([power, b, d + 1], [a, power, d + 1])
        }
        nq.sort((a, b) => {
            if (a[0] === b[0]) {
                return b[1] - a[1]
            } else {
                return b[0] - a[0]
            }
        })
// console.log(nq)
        q = []
        let ma = 0
        let mb = 0
        for (let i = 0; i < nq.length; i++) {
            const [a, b, d] = nq[i];
            if (a >= n && b >= m) return d
            if (a <= ma && b <= mb) continue
            ma = Math.max(ma, a)
            mb = Math.max(mb, b)
            q.push([a, b, d])
        }
        if (!q.length) break
    }
    return -1
}
function key(a, b) {
    return a + ',' + b
}


The company "Divan's Sofas" is planning to build $$$n + 1$$$ different buildings on a coordinate line so that:   the coordinate of each building is an integer number;  no two buildings stand at the same point. Let $$$x_i$$$ be the coordinate of the $$$i$$$-th building. To get from the building $$$i$$$ to the building $$$j$$$, Divan spends $$$|x_i - x_j|$$$ minutes, where $$$|y|$$$ is the absolute value of $$$y$$$.All buildings that Divan is going to build can be numbered from $$$0$$$ to $$$n$$$. The businessman will live in the building $$$0$$$, the new headquarters of "Divan's Sofas". In the first ten years after construction Divan will visit the $$$i$$$-th building $$$a_i$$$ times, each time spending $$$2 \cdot |x_0-x_i|$$$ minutes for walking.Divan asks you to choose the coordinates for all $$$n + 1$$$ buildings so that over the next ten years the businessman will spend as little time for walking as possible.

Each test contains several test cases. The first line contains one integer number $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of test cases. The first line of each case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of buildings that "Divan's Sofas" is going to build, apart from the headquarters. The second line contains the sequence $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^6$$$), where $$$a_i$$$ is the number of visits to the $$$i$$$-th building. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, on the first line print the number $$$T$$$ — the minimum time Divan will spend walking.  On the second line print the sequence $$$x_0, x_1, \ldots, x_n$$$ of $$$n + 1$$$ integers, where $$$x_i$$$ ($$$-10^6 \le x_i \le 10^6$$$) is the selected coordinate of the $$$i$$$-th building. It can be shown that an optimal answer exists with coordinates not exceeding $$$10^6$$$. If there are multiple answers, print any of them.

NoteLet's look at the first example.Divan will visit the first building $$$a_1 = 1$$$ times, the second $$$a_2 = 2$$$ times and the third $$$a_3 = 3$$$ times. Then one of the optimal solution will be as follows:   the headquarters is located in $$$x_0 = 2$$$;  $$$x_1 = 4$$$: Divan will spend $$$2 \cdot |x_0-x_1| \cdot a_1 = 2 \cdot |2-4| \cdot 1 = 4$$$ minutes walking to the first building;  $$$x_2 = 1$$$: Divan will spend $$$2 \cdot |x_0-x_2| \cdot a_2 = 2 \cdot |2-1| \cdot 2 = 4$$$ minutes walking to the second building;  $$$x_3 = 3$$$: Divan will spend $$$2 \cdot |x_0-x_3| \cdot a_3 = 2 \cdot |2-3| \cdot 3 = 6$$$ minutes walking to the third building. In total, Divan will spend $$$4 + 4 + 6 = 14$$$ minutes. It can be shown that it is impossible to arrange buildings so that the businessman spends less time.Among others, $$$x = [1, 3, 2, 0]$$$, $$$x = [-5, -3, -6, -4]$$$ are also correct answers for the first example.

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

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

let count = -1
let inputArr = []

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

function solve([n], arr) {
    const mp = arr.map((i, index) => ([i, index])).sort((a, b) => a[0] - b[0]).reverse()
    const ans = new Array(n).fill(0)
    let currentSide = true;
    let k = 1
    let minTime = 0;
    mp.forEach((i) => {
        let index = i[1]
        if (currentSide) {
            ans[index] = k
        } else {
            ans[index] = -k
            k++
        }
        currentSide = !currentSide
    })
    for (let i = 0; i < n; i++) {
        minTime += (2 * Math.abs(ans[i]) * arr[i]);
    }
    console.log(minTime)
    console.log(0 + ' ' + ans.join(' '))
}

function main() {

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

const readline = require('readline')

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

function solve(n, arr) {
    const sorted = arr.map((x, i) => ({ x, i }))
        .sort((a, b) => b.x - a.x)
    let left = -1
    let right = 1
    const ans = Array(n)
    ans[0] = 0
    let d = 0
    for (let i = 0; i < sorted.length; i++) {
        ans[sorted[i].i + 1] = (i & 1) ? right++ : left--
        d += 2 * Math.abs(ans[sorted[i].i + 1]) * sorted[i].x
    }
    return d + '\n' + ans.join(' ')
}

const solve = (arr)=>{
     let narr = [];
     for(let i=0;i<arr.length;i++){
          let obj = {"val" : arr[i],"ind" : i};
          narr.push(obj);
     }
     narr.sort((a,b)=>b.val - a.val);
     let plus = 1,minus = 1,k=0,res = 0,obj = [];
     for(let i=0;i<narr.length;i++){
          if(!k){
               plus++;
               res += Math.abs(1-plus)*2*narr[i]["val"];
               obj[narr[i]["ind"]] = plus;
          }
          else{
               minus--;
               res+=Math.abs(1-minus)*2*narr[i]["val"];
               obj[narr[i]["ind"]] = minus;
          }
          k = !k;
     }
     console.log(res);
     let r = "1 ";
     for(let i=0;i<obj.length;i++) r+=obj[i]+" ";
     console.log(r);
}
function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for(let i=0;i<t;i++){
       let n = parseInt(readline());
       let arr = readline().trim().split(" ").map(cur=>parseInt(cur));
       solve(arr);
  }
}
main();

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

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

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

		for (let i = 0; i < n; i++) {
			a[i] = [a[i], i];
		}
		a.sort((x, y) => y[0] - x[0]);

		const ans = [0];
		let dist = 0;
		for (let i = 0; i < n; i++) {
			ans[a[i][1]+1] = Math.ceil((i+1)/2) * (i&1 ? 1 : -1);
			dist += 2*a[i][0]*Math.abs(ans[a[i][1]+1]);
		}

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

//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 = new Array(N);
		for(var i = 0; i < N; i++){
			list[i] = {
				no : i,
				count : nextInt()
			};
		}
		list.sort(function(a,b){
			return b.count - a.count;
		});
		var output = new Array(N + 1);
		output[0] = 0;
		var sum = 0;
		for(var i = 0; i < N; i++){
			var index = Math.floor(i / 2) + 1;
			if(i % 2 == 1){
				index *= -1;
			}
			output[list[i].no + 1] = index;
			sum += 2 * Math.abs(index) * list[i].count;
		}
		myout(sum);
		myout(myconv(output, 8));
	}
}

var t = parseInt(readline());

  while (t--) {
    var n = parseInt(readline());
    var input2 = readline().split(" ");
    var arr = [];
    for (var i = 0; i < n; i++) {
      arr.push({
        value: parseInt(input2[i]),
        index: i,
      });
    }

    arr.sort((a, b) => {
      if (a.value > b.value) {
        return 1;
      } else if (a.value < b.value) {
        return -1;
      } else {
        return 0;
      }
    });

    var time = 0;
    var ans = [];
    var idx = 1;
    for (var i = n - 1; i >= 0; i -= 2) {
      var temp = 2 * idx;
      time = time + arr[i].value * temp;
      ans[arr[i].index] = idx;
      idx++;
    }

    idx = -1;
    for (var i = n - 2; i >= 0; i -= 2) {
      var temp = 2 * Math.abs(idx);
      time = time + arr[i].value * temp;
      ans[arr[i].index] = idx;
      idx--;
    }
    print(time);
    var val = "0 ";
    for (var i = 0; i < n; i++) val += ans[i] + " ";
    print(val);
  }

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

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

let count = -1
let inputArr = []

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

function solve([n], arr) {
    const mp = arr.map((i, index) => ([i, index])).reverse()
    const ans = new Array(n).fill(0)
    let currentSide = true;
    let k = 1
    let minTime = 0;
    mp.forEach((i) => {
        let value = i[0]
        let index = i[1]
        if (currentSide) {
            ans[index] = k
        } else {
            ans[index] = -k
            k++
        }
        currentSide = !currentSide
    })
    for (let i = 0; i < n; i++) {
        minTime += (2 * Math.abs(ans[i]) * arr[i]);
    }
    console.log(minTime)
    console.log(0 + ' ' + ans.join(' '))
}

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

const readline = require('readline')

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

function solve(n, arr) {
    const sorted = arr.map((x, i) => ({ x, i }))
        .sort((a, b) => b.x - a.x)
    let left = -1
    let right = 1
    const ans = Array(n)
    ans[0] = 0
    for (let i = 0; i < sorted.length; i++) {
        ans[sorted[i].i + 1] = (i & 1) ? right++ : left--
    }
    return ans.join(' ')
}

  var t = parseInt(readline());

  while (t--) {
    var n = parseInt(readline());
    var input2 = readline().split(" ");
    var arr = [];
    for (var i = 0; i < n; i++) {
      arr.push({
        value: parseInt(input2[i]),
        index: i,
      });
    }

    arr.sort((a, b) => {
      if (a.value > b.value) {
        return 1;
      } else if (a.value < b.value) {
        return -1;
      } else {
        return 0;
      }
    });

    var time = 0;
    var ans = [];
    var idx = 1;
    for (var i = n - 1; i >= 0; i -= 2) {
      var temp = 2 * idx;
      time = time + arr[i].value * temp;
      ans[arr[i].index] = idx;
      idx++;
    }

    idx = -1;
    for (var i = n - 2; i >= 0; i -= 2) {
      var temp = 2 * Math.abs(idx);
      time = time + arr[i].value * temp;
      ans[arr[i].index] = idx;
      idx--;
    }
    print(time);
    var val = "";
    for (var i = 0; i < n; i++) val += ans[i] + " ";
    print(val);
  }


Nezzar's favorite digit among $$$1,\ldots,9$$$ is $$$d$$$. He calls a positive integer lucky if $$$d$$$ occurs at least once in its decimal representation. Given $$$q$$$ integers $$$a_1,a_2,\ldots,a_q$$$, for each $$$1 \le i \le q$$$ Nezzar would like to know if $$$a_i$$$ can be equal to a sum of several (one or more) lucky numbers.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 9$$$) — the number of test cases. The first line of each test case contains two integers $$$q$$$ and $$$d$$$ ($$$1 \le q \le 10^4$$$, $$$1 \le d \le 9$$$). The second line of each test case contains $$$q$$$ integers $$$a_1,a_2,\ldots,a_q$$$ ($$$1 \le a_i \le 10^9$$$).

For each integer in each test case, print "YES" in a single line if $$$a_i$$$ can be equal to a sum of lucky numbers. Otherwise, print "NO". You can print letters in any case (upper or lower).

YES
NO
YES
YES
YES
NO
YES
YES
YES
YES
YES
YES
NO

NoteIn the first test case, $$$24 = 17 + 7$$$, $$$27$$$ itself is a lucky number, $$$25$$$ cannot be equal to a sum of lucky numbers.

"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());
  const precheck = (n, d) => {
    while (n > 0) {
      if (n % 10 === d) return true;
      n = Math.floor(n / 10);
    }
    return false;
  };
  while (t--) {
    let [n, d] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    for (let i = 0; i < n; i++) {
      if (d === 1) console.log("YES");
      else if (arr[i] >= d * 10) console.log("YES");
      else {
        let flag = false;
        let k = arr[i];
        while (k > 0) {
          if (precheck(k, d)) {
            flag = true;
            break;
          }
          k = k - d;
        }
        console.log(`${flag === true ? "YES" : "NO"}`);
      }
    }
  }
};
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{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);}
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();
	for(var i = 0; i < t; i++){
		var N = nextInt();
		var d = nextInt();
		for(var j = 0; j < N; j++){
			var a = nextInt();
			if(a % d == 0){
				myout("YES");
				continue;
			}
			var tmp = a;
			var isOK = false;
			while(tmp > 0){
				if(tmp % 10 == d){
					isOK = true;
					break;
				}
				tmp = Math.floor(tmp / 10);
			}
			var p = a % d;
			for(var k = 1; k <= Math.floor(a / d); k++){
				var tmp = (k * d + p);
				while(tmp > 0){
					if(tmp % 10 == d){
						isOK = true;
						break;
					}
					tmp = Math.floor(tmp / 10);
				}
				if(isOK){
					break;
				}
			}

			if(isOK){
				myout("YES");
			}else{
				myout("NO");
			}
		}
	}
}

process.stdin.resume();
process.stdin.setEncoding("utf8");
let standardInputString = "";
let curLine = 0;

function readLine() {
  return standardInputString[curLine++];
}

process.stdin.on("data", rawData => {
  standardInputString += rawData;
});

process.stdin.on("end", _ => {
  standardInputString = standardInputString
    .trim()
    .split("\n")
    .map(line => {
      return line.trim();
    });

  main();
});

// Pilot course from ITMO -> Z-function -> Step 1 -> Problem A

// function main() {
//   const testQuantity = +readLine();
//   for (let testNumber = 0; testNumber < testQuantity; testNumber++) {
//     let inputString = readLine();
//     let curLen = 0;
//     let curPrefix = "";
//     let maxPrefixLen = 0;

//     for (let inputChar of inputString) {
//       curPrefix += inputChar;
//       curLen++;

//       let foundNew = true;
//       let medianIndex = Math.floor(curLen / 2);
//       for (; medianIndex >= 0; medianIndex--) {
//         if (curPrefix[curLen - 1 - medianIndex] !== curPrefix[medianIndex]) {
//           foundNew = false;
//           break;
//         }
//       }

//       if (foundNew) {
//         maxPrefixLen = curLen;
//       }
//     }

//     console.log(maxPrefixLen);
//   }
// }

// .. -> Problem B

// function main() {
//   const testQuan = +readLine();
//   for (let testIx = 0; testIx < testQuan; testIx++) {
//     const inputStr = readLine();
//     let counter = 0;

//     for (let curLen = 0; curLen <= inputStr.length; curLen++) {
//       for (let startIx = 0; curLen + startIx <= inputStr.length; startIx++) {
//         let substring = inputStr.substring(startIx, startIx + curLen);
//         let prefix = inputStr.substring(0, curLen);
//         let suffix = inputStr.slice(inputStr.length - curLen, inputStr.length);

//         if (substring === prefix && substring !== suffix || substring === suffix && substring !== prefix) {
//           counter++;
//         }
//       }
//     }

//     console.log(counter);
//   }
// }

// .. -> Problem C

// function match(text, pattern) {
//   if (pattern.length > text.length) {
//     return false;
//   }

//   for (let comparingIx = 0; comparingIx < text.length; comparingIx++) {
//     if (text[comparingIx] !== pattern[comparingIx] && pattern[comparingIx] !== "?") {
//       return false;
//     }
//   }

//   return true;
// }

// function main() {
//   const testQuan = +readLine();
//   for (let testIx = 0; testIx < testQuan; testIx++) {
//     const inputStr = readLine();
//     const inputPattern = readLine();
//     const entryIndexes = [];

//     for (let startIx = 0; startIx + inputPattern.length <= inputStr.length; startIx++) {
//       if ( match(inputStr.slice(startIx, startIx + inputPattern.length), inputPattern) ) {
//         entryIndexes.push(startIx);
//       }
//     }

//     console.log(entryIndexes.length);
//     console.log(entryIndexes.join(" "));
//   }
// }

// .. -> Problem D

// function getSubstrQuan(length) {
//   return (length + 1) * (length) / 2;
// }

// function main() {
//   const testQuan = +readLine();
//   for (let testIx = 0; testIx < testQuan; testIx++) {
//     const inputStr = readLine();
//     const inputPattern = readLine();
//     let entryBorders = [];
//     let counter = 0;

//     for (let startIx = 0; startIx + inputPattern.length <= inputStr.length; startIx++) {
//       if ( inputStr.slice(startIx, startIx + inputPattern.length).includes(inputPattern) ) {
//         entryBorders.push([startIx, startIx + inputPattern.length - 1]);
//       }
//     }

//     entryBorders.push([inputStr.length, inputStr.length]);
//     let lastLeftBorder = 0;
//     for (let pairIx = 0; pairIx < entryBorders.length; pairIx++) {
//       let curPair = entryBorders[pairIx];
//       let curSubstrLen = curPair[1] - lastLeftBorder;
//       counter += getSubstrQuan(curSubstrLen);
//       lastLeftBorder = curPair[0] + 1;

//       if (curPair[1] - curPair[0] - 1 > 0) {
//         counter -= getSubstrQuan(curPair[1] - curPair[0] - 1);
//       }
//     }

//     console.log(counter);
//   }
// }

// Codeforces Round #698 (Div. 2) -> Problem A

// function main() {
//   let testQuan = +readLine();
//   for (let testIx = 0; testIx < testQuan; testIx++) {
//     let n = +readLine();
//     let a = readLine().split(" ");
//     a = a.map(item => +item);
//     let counterArr = [];
//     for (let i = 0; i <= n; i++) counterArr[i] = 0;

//     for (let el of a) {
//       counterArr[el]++;
//     }

//     console.log(Math.max(...counterArr));
//   }
// }

// .. -> Problem B

function main() {
  const testQuan = +readLine();
  for (let testIx = 0; testIx < testQuan; testIx++) {
    let [, d] = readLine().split(" ").map(item => +item);
    let a = readLine().split(" ").map(item => +item);

    let possibleLastDigits = [];
    for (let multiplier = 1; multiplier < 11; multiplier++) {
      possibleLastDigits.push(d * multiplier % 10);
    }

    let canGain = num => {
      let curLastDigit = num % 10;
      let multiplier = possibleLastDigits.indexOf(curLastDigit) + 1;

      return multiplier ? multiplier * d <= num : false;
    };

    for (let item of a) {
      let flag = canGain(item) || String(item).includes(`${d}`);
      // console.log(item + ", " + flag);
      for (let i = 0; i < 10; i++) {
        let tmp = item;
        // console.log(tmp, i);
        tmp -= d * 10 + i;
        // console.log(tmp);

        if (tmp > 0) {
          flag = flag || canGain(tmp);
        }
        // console.log(flag);
      }

      console.log(flag ? "YES" : "NO");
    }
  }
}

// .. -> Problem C

// function main() {

// }

'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++];
}
/**
2
3 7
24 25 27
10 7
51 52 53 54 55 56 57 58 59 60
**/

function gcd(a, b) {
    if (!b) {
        return a;
    }

    return gcd(b, a % b);
};

function lcm(a, b) {
    return (a / gcd(a, b) * b);
}

function main() {
    let n = Number(readline());

    for(let r=0;r<n;r++) {
        solve();
    }

}

function solve() {
    let [q, d] = readline().split(" ");
    let a = readline().split(" ");
    let map = {};

    for(let i=0;i<a.length;i++) {
        if(a[i].includes(d)) {
            map[a[i]] = 'Yes';
            console.log('Yes');
        } else {
            let number = Number(d);
            let current = Number(a[i]);
            let found = false;
            while(!found && current > number) {
                current = current - number;

                if (map[current]) {
                    console.log(map[current]);
                    found = true;
                }else if (("" + current).includes(d)) {
                    map[current] = 'Yes';

                    console.log(map[current]);
                    found = true;
                }
            }

            if(found === false) {
                map[a[i]] = 'No';
                console.log("No");
            }
        }
    }

}

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.split('\n').map(str => str.trim());

  main();
});

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

function main() {
  let t = readline();

  while (t--) {
    const d = readline().split(' ').map(num => parseInt(num, 10))[1];
    const q = readline().split(' ').map(num => parseInt(num, 10));

    q.forEach(n => {
      let r = '';

      for (let i = n; i > 0; i -= d) {
        const iar = `${i}`.includes(d);

        if (iar) {
          r = 'YES';
          break;
        } else {
          r = 'NO';
        }
      }

      console.log(r);
    });
  }
}

'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 x = readline();
    var answer = []

    // console.log(Number(x))
    // 1 1 7
    // 6 9, 15, 18
    Array(Number(x)).fill(1).map((t, i) => {
        var [q, d] = readline().split(' ').map(x => Number(x));
        var array = readline().split(' ').map(x => Number(x));
        var answer = {}
        for (var i = 0; i < 100; i++) {
            answer[i] = true
        }
        for (var i = 0; i < 100; i++) {
            answer[i * d] = false
            answer[i * d + Number(`1${d}`)] = false
            answer[i * d + Number(`2${d}`)] = false
            answer[i * d + Number(`3${d}`)] = false
            answer[i * d + Number(`4${d}`)] = false
            answer[i * d + Number(`5${d}`)] = false
            answer[i * d + Number(`6${d}`)] = false
            answer[i * d + Number(`7${d}`)] = false
            answer[i * d + Number(`8${d}`)] = false
            answer[i * d + Number(`9${d}`)] = false
            answer[i * d + Number(`${d}0`)] = false
            answer[i * d + Number(`${d}1`)] = false
            answer[i * d + Number(`${d}2`)] = false
            answer[i * d + Number(`${d}3`)] = false
            answer[i * d + Number(`${d}4`)] = false
            answer[i * d + Number(`${d}5`)] = false
            answer[i * d + Number(`${d}6`)] = false
            answer[i * d + Number(`${d}7`)] = false
            answer[i * d + Number(`${d}8`)] = false
            answer[i * d + Number(`${d}9`)] = false
        }
        // console.log(answer)
        // for (var i = 0; i < 100; i++) {
        //     if (answer[i]) console.log(i)
        // }
        array.map((x,i)=>{
        console.log(!answer[x] ? 'YES':'NO')
        })

    })

}

"use strict"

let iter = parseInt(readline());

while(iter--){
    let temp = readline().split(" ").map(x => parseInt(x));
    let length = temp[0];
    let d = temp[1];
    let input = readline().split(" ");

    let obj = {
        "0" : null,
        "1" : null,
        "2" : null,
        "3" : null,
        "4" : null,
        "5" : null,
        "6" : null,
        "7" : null,
        "8" : null,
        "9" : null,
    };

    for(let i = 1; i < 11; i++){
        let t = String(i * d)
        if(obj[t[t.length - 1]] === null){
            obj[t[t.length - 1]] = parseInt(t);
        }
    }

    for(let i = 0; i < length; i++){
        let t = input[i][input[i].length - 1];
        if(obj[t] === null){
            if(parseInt(input[i]) > d * 10){
                print("YES");
            } else {
                print("NO")
            }
        } else if(obj[t] <= parseInt(input[i])){
            print("YES")
        } else {
            print("NO")
        }
    }
}

function solve(a,n){
    var l = 0;

    while(l < a.length){
        var f = true;
        if(String(a[l]).includes(String(n))){
            write("YES\n");
        }else{
            var aux = a[l];
            while(aux > 0){
                aux = aux - Number(n);
                if(String(aux).includes(String(n))){
                    write("YES\n");
                    f = false;
                    break;
                }
            }
            if(f){
                write("NO\n");
            }
        }
        l++;
    }

}

var a = [];
var t = Number(readline());
for (var i = 0; i<t;i++){
    n = readline().split(' ').map((x) => x);
    a = readline().split(' ').map((x) => x);
    solve(a,n[1]);
}

"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++];
}
let dp = [];
const precompute = () => {
  for (let i = 2; i <= 9; i++) {
    let k = [];
    for (let j = 0; j <= 9; j++) {
      k.push(i * (j + 1));
    }
    dp.push(k);
  }
};
const solve = () => {
  let t = parseInt(readline());
  precompute();
  const precheck = (n, d) => {
    while (n > 0) {
      if (n % 10 === d) return true;
      n = Math.floor(n / 10);
    }
    return false;
  };
  while (t--) {
    let [n, d] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    for (let i = 0; i < n; i++) {
      if (d === 1) console.log("YES");
      else if (precheck(arr[i], d)) console.log("YES");
      else {
        let flag = false;
        for (let j = 0; j <= 9; j++) {
          if (dp[d - 2][j] % 10 === arr[i] % 10) {
            if (arr[i] >= dp[d - 2][j]) {
              flag = true;
              break;
            }
          }
        }
        console.log(`${flag === true ? "YES" : "NO"}`);
      }
    }
  }
};
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++];
}
let dp = [];
const precompute = () => {
  for (let i = 2; i <= 9; i++) {
    let k = [];
    for (let j = 0; j <= 9; j++) {
      k.push(i * (j + 1));
    }
    dp.push(k);
  }
};
const solve = () => {
  let t = parseInt(readline());
  precompute();
  const precheck = (n, d) => {
    while (n > 0) {
      if (n % 10 === d) return true;
      n = Math.floor(n / 10);
    }
    return false;
  };
  while (t--) {
    let [n, d] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    for (let i = 0; i < n; i++) {
      if (d === 1) console.log("YES");
      else if (precheck(arr[i], d)) console.log("YES");
      else {
        let flag = false;
        for (let j = 0; j <= 9; j++) {
          if (dp[d - 2][j] % 10 === arr[i] % 10) {
            flag = dp[d - 2][j] <= arr[i] ? true : false;
          }
        }
        console.log(`${flag === true ? "YES" : "NO"}`);
      }
    }
  }
};
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++];
}
let dp = [];
const precompute = () => {
  for (let i = 2; i <= 9; i++) {
    let k = [];
    for (let j = 0; j <= 9; j++) {
      k.push(i * (j + 1));
    }
    dp.push(k);
  }
};
const solve = () => {
  let t = parseInt(readline());
  precompute();
  const precheck = (n, d) => {
    while (n > 0) {
      if (n % 10 === d) return true;
      n = Math.floor(n / 10);
    }
    return false;
  };
  while (t--) {
    let [n, d] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    for (let i = 0; i < n; i++) {
      if (d === 1) console.log("YES");
      else if (precheck(arr[i], d)) console.log("YES");
      else {
        let flag = false;
        for (let j = 0; j <= 9; j++) {
          if (dp[d - 2][j] % 10 === arr[i] % 10) {
            flag = dp[d - 2][j] <= arr[i] ? true : false;
            break;
          }
        }
        console.log(`${flag === true ? "YES" : "NO"}`);
      }
    }
  }
};
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++];
}
let dp = [];
const precompute = () => {
  for (let i = 2; i <= 9; i++) {
    let k = [];
    for (let j = 0; j <= 9; j++) {
      k.push(i * (j + 1));
    }
    dp.push(k);
  }
};
const solve = () => {
  let t = parseInt(readline());
  precompute();
  const precheck = (n, d) => {
    while (n > 0) {
      if (n % 10 === d) return true;
      n = Math.floor(n / 10);
    }
    return false;
  };
  while (t--) {
    let [n, d] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    for (let i = 0; i < n; i++) {
      if (d === 1) console.log("YES");
      else if (precheck(arr[i], d)) console.log("YES");
      else {
        let flag = false;
        for (let j = 0; j < 9; j++) {
          if (dp[d - 2][j] % 10 === arr[i] % 10) {
            flag = dp[d - 2][j] <= arr[i] ? true : false;
            break;
          }
        }
        console.log(`${flag === true ? "YES" : "NO"}`);
      }
    }
  }
};
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++];
}
let dp = [];
const precompute = () => {
  for (let i = 2; i <= 9; i++) {
    let k = [];
    for (let j = 0; j < 9; j++) {
      k.push(i * (j + 1));
    }
    dp.push(k);
  }
};
const solve = () => {
  let t = parseInt(readline());
  precompute();
  const precheck = (n, d) => {
    while (n > 0) {
      if (n % 10 === d) return true;
      n = Math.floor(n / 10);
    }
    return false;
  };
  while (t--) {
    let [n, d] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    for (let i = 0; i < n; i++) {
      if (d === 1) console.log("YES");
      else if (precheck(arr[i], d)) console.log("YES");
      else {
        let flag = false;
        for (let j = 0; j < 9; j++) {
          if (dp[d - 2][j] % 10 === arr[i] % 10) {
            flag = dp[d - 2][j] <= arr[i] ? true : false;
            break;
          }
        }
        console.log(`${flag === true ? "YES" : "NO"}`);
      }
    }
  }
};
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{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);}
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();
	for(var i = 0; i < t; i++){
		var N = nextInt();
		var d = nextInt();
		for(var j = 0; j < N; j++){
			var a = nextInt();
			if(a % d == 0){
				myout("YES");
				continue;
			}
			var tmp = a;
			var isOK = false;
			while(tmp > 0){
				if(tmp % 10 == d){
					isOK = true;
					break;
				}
				tmp = Math.floor(tmp / 10);
			}
			var p = a % d;
			for(var k = 1; k <= Math.min(100, Math.floor(a / d)); k++){
				if((k * d + p) % 10 == d){
					isOK = true;
					break;
				}
			}

			if(isOK){
				myout("YES");
			}else{
				myout("NO");
			}
		}
	}
}

//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{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);}
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();
	for(var i = 0; i < t; i++){
		var N = nextInt();
		var d = nextInt();
		for(var j = 0; j < N; j++){
			var a = nextInt();
			if(a % d == 0){
				myout("YES");
				continue;
			}
			var tmp = a;
			var isOK = false;
			while(tmp > 0){
				if(tmp % 10 == d){
					isOK = true;
					break;
				}
				tmp = Math.floor(tmp / 10);
			}
			var p = a % d;
			for(var k = 1; k <= Math.min(9, Math.floor(a / d)); k++){
				if((k * d + p) % 10 == d){
					isOK = true;
					break;
				}
			}

			if(isOK){
				myout("YES");
			}else{
				myout("NO");
			}
		}
	}
}

//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{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);}
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();
	for(var i = 0; i < t; i++){
		var N = nextInt();
		var d = nextInt();
		for(var j = 0; j < N; j++){
			var a = nextInt();
			if(a % d == 0){
				myout("YES");
				continue;
			}
			var tmp = a;
			var isOK = false;
			while(tmp > 0){
				if(tmp % d == 0){
					isOK = true;
					break;
				}
				tmp = Math.floor(tmp / 10);
			}
			var p = a % d;
			for(var k = 1; k <= Math.min(9, Math.floor(a / d)); k++){
				if((k * d + p) % 10 == d){
					isOK = true;
					break;
				}
			}

			if(isOK){
				myout("YES");
			}else{
				myout("NO");
			}
		}
	}
}

//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{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);}
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();
	for(var i = 0; i < t; i++){
		var N = nextInt();
		var d = nextInt();
		for(var j = 0; j < N; j++){
			var a = nextInt();
			if(a % 10 == d || a % d == 0){
				myout("YES");
				continue;
			}
			var tmp = a;
			var isOK = false;
			while(tmp > 0){
				if(tmp % d == 0){
					isOK = true;
					break;
				}
				tmp = Math.floor(tmp / 10);
			}
			var p = a % d;
			for(var k = 1; k <= Math.min(9, Math.floor(a / d)); k++){
				if((k * d + p) % 10 == d){
					isOK = true;
					break;
				}
			}

			if(d + p == 10){
				isOK = true;
			}
			if(isOK){
				myout("YES");
			}else{
				myout("NO");
			}
		}
	}
}

process.stdin.resume();
process.stdin.setEncoding("utf8");
let standardInputString = "";
let curLine = 0;

function readLine() {
  return standardInputString[curLine++];
}

process.stdin.on("data", rawData => {
  standardInputString += rawData;
});

process.stdin.on("end", _ => {
  standardInputString = standardInputString
    .trim()
    .split("\n")
    .map(line => {
      return line.trim();
    });

  main();
});

// Pilot course from ITMO -> Z-function -> Step 1 -> Problem A

// function main() {
//   const testQuantity = +readLine();
//   for (let testNumber = 0; testNumber < testQuantity; testNumber++) {
//     let inputString = readLine();
//     let curLen = 0;
//     let curPrefix = "";
//     let maxPrefixLen = 0;

//     for (let inputChar of inputString) {
//       curPrefix += inputChar;
//       curLen++;

//       let foundNew = true;
//       let medianIndex = Math.floor(curLen / 2);
//       for (; medianIndex >= 0; medianIndex--) {
//         if (curPrefix[curLen - 1 - medianIndex] !== curPrefix[medianIndex]) {
//           foundNew = false;
//           break;
//         }
//       }

//       if (foundNew) {
//         maxPrefixLen = curLen;
//       }
//     }

//     console.log(maxPrefixLen);
//   }
// }

// .. -> Problem B

// function main() {
//   const testQuan = +readLine();
//   for (let testIx = 0; testIx < testQuan; testIx++) {
//     const inputStr = readLine();
//     let counter = 0;

//     for (let curLen = 0; curLen <= inputStr.length; curLen++) {
//       for (let startIx = 0; curLen + startIx <= inputStr.length; startIx++) {
//         let substring = inputStr.substring(startIx, startIx + curLen);
//         let prefix = inputStr.substring(0, curLen);
//         let suffix = inputStr.slice(inputStr.length - curLen, inputStr.length);

//         if (substring === prefix && substring !== suffix || substring === suffix && substring !== prefix) {
//           counter++;
//         }
//       }
//     }

//     console.log(counter);
//   }
// }

// .. -> Problem C

// function match(text, pattern) {
//   if (pattern.length > text.length) {
//     return false;
//   }

//   for (let comparingIx = 0; comparingIx < text.length; comparingIx++) {
//     if (text[comparingIx] !== pattern[comparingIx] && pattern[comparingIx] !== "?") {
//       return false;
//     }
//   }

//   return true;
// }

// function main() {
//   const testQuan = +readLine();
//   for (let testIx = 0; testIx < testQuan; testIx++) {
//     const inputStr = readLine();
//     const inputPattern = readLine();
//     const entryIndexes = [];

//     for (let startIx = 0; startIx + inputPattern.length <= inputStr.length; startIx++) {
//       if ( match(inputStr.slice(startIx, startIx + inputPattern.length), inputPattern) ) {
//         entryIndexes.push(startIx);
//       }
//     }

//     console.log(entryIndexes.length);
//     console.log(entryIndexes.join(" "));
//   }
// }

// .. -> Problem D

// function getSubstrQuan(length) {
//   return (length + 1) * (length) / 2;
// }

// function main() {
//   const testQuan = +readLine();
//   for (let testIx = 0; testIx < testQuan; testIx++) {
//     const inputStr = readLine();
//     const inputPattern = readLine();
//     let entryBorders = [];
//     let counter = 0;

//     for (let startIx = 0; startIx + inputPattern.length <= inputStr.length; startIx++) {
//       if ( inputStr.slice(startIx, startIx + inputPattern.length).includes(inputPattern) ) {
//         entryBorders.push([startIx, startIx + inputPattern.length - 1]);
//       }
//     }

//     entryBorders.push([inputStr.length, inputStr.length]);
//     let lastLeftBorder = 0;
//     for (let pairIx = 0; pairIx < entryBorders.length; pairIx++) {
//       let curPair = entryBorders[pairIx];
//       let curSubstrLen = curPair[1] - lastLeftBorder;
//       counter += getSubstrQuan(curSubstrLen);
//       lastLeftBorder = curPair[0] + 1;

//       if (curPair[1] - curPair[0] - 1 > 0) {
//         counter -= getSubstrQuan(curPair[1] - curPair[0] - 1);
//       }
//     }

//     console.log(counter);
//   }
// }

// Codeforces Round #698 (Div. 2) -> Problem A

// function main() {
//   let testQuan = +readLine();
//   for (let testIx = 0; testIx < testQuan; testIx++) {
//     let n = +readLine();
//     let a = readLine().split(" ");
//     a = a.map(item => +item);
//     let counterArr = [];
//     for (let i = 0; i <= n; i++) counterArr[i] = 0;

//     for (let el of a) {
//       counterArr[el]++;
//     }

//     console.log(Math.max(...counterArr));
//   }
// }

// .. -> Problem B

function main() {
  let testQuan = +readLine();
  for (let testIx = 0; testIx < testQuan; testIx++) {
    let [d, q] = readLine().split(" ").map(item => +item);
    let a = readLine().split(" ").map(item => +item);
    let possibleLastDigits = [];

    for (let multiplier = 1; multiplier < 11; multiplier++) {
      possibleLastDigits.push(multiplier * q % 10);
    }

    for (let el of a) {
      let curLastDigit = el % 10;

      if (q % 2 === 0 && el % 2 === 1) {
        el -= q * 10 + curLastDigit;

        if (el < 0) {
          console.log("NO");
          continue;
        } else if (el === 0) {
          console.log("YES");
          continue;
        }
      }

      curLastDigit = el % 10;
      let luckyNumsQuan = possibleLastDigits.indexOf(curLastDigit) + 1;

      if ( !possibleLastDigits.includes(curLastDigit) || luckyNumsQuan === -1 || luckyNumsQuan * q > el ) {
        console.log("NO");
        continue;
      }

      console.log("YES");
    }
  }
}

// .. -> Problem C

// function main() {

// }

process.stdin.resume();
process.stdin.setEncoding("utf8");
let standardInputString = "";
let curLine = 0;

function readLine() {
  return standardInputString[curLine++];
}

process.stdin.on("data", rawData => {
  standardInputString += rawData;
});

process.stdin.on("end", _ => {
  standardInputString = standardInputString
    .trim()
    .split("\n")
    .map(line => {
      return line.trim();
    });

  main();
});

// Pilot course from ITMO -> Z-function -> Step 1 -> Problem A

// function main() {
//   const testQuantity = +readLine();
//   for (let testNumber = 0; testNumber < testQuantity; testNumber++) {
//     let inputString = readLine();
//     let curLen = 0;
//     let curPrefix = "";
//     let maxPrefixLen = 0;

//     for (let inputChar of inputString) {
//       curPrefix += inputChar;
//       curLen++;

//       let foundNew = true;
//       let medianIndex = Math.floor(curLen / 2);
//       for (; medianIndex >= 0; medianIndex--) {
//         if (curPrefix[curLen - 1 - medianIndex] !== curPrefix[medianIndex]) {
//           foundNew = false;
//           break;
//         }
//       }

//       if (foundNew) {
//         maxPrefixLen = curLen;
//       }
//     }

//     console.log(maxPrefixLen);
//   }
// }

// .. -> Problem B

// function main() {
//   const testQuan = +readLine();
//   for (let testIx = 0; testIx < testQuan; testIx++) {
//     const inputStr = readLine();
//     let counter = 0;

//     for (let curLen = 0; curLen <= inputStr.length; curLen++) {
//       for (let startIx = 0; curLen + startIx <= inputStr.length; startIx++) {
//         let substring = inputStr.substring(startIx, startIx + curLen);
//         let prefix = inputStr.substring(0, curLen);
//         let suffix = inputStr.slice(inputStr.length - curLen, inputStr.length);

//         if (substring === prefix && substring !== suffix || substring === suffix && substring !== prefix) {
//           counter++;
//         }
//       }
//     }

//     console.log(counter);
//   }
// }

// .. -> Problem C

// function match(text, pattern) {
//   if (pattern.length > text.length) {
//     return false;
//   }

//   for (let comparingIx = 0; comparingIx < text.length; comparingIx++) {
//     if (text[comparingIx] !== pattern[comparingIx] && pattern[comparingIx] !== "?") {
//       return false;
//     }
//   }

//   return true;
// }

// function main() {
//   const testQuan = +readLine();
//   for (let testIx = 0; testIx < testQuan; testIx++) {
//     const inputStr = readLine();
//     const inputPattern = readLine();
//     const entryIndexes = [];

//     for (let startIx = 0; startIx + inputPattern.length <= inputStr.length; startIx++) {
//       if ( match(inputStr.slice(startIx, startIx + inputPattern.length), inputPattern) ) {
//         entryIndexes.push(startIx);
//       }
//     }

//     console.log(entryIndexes.length);
//     console.log(entryIndexes.join(" "));
//   }
// }

// .. -> Problem D

// function getSubstrQuan(length) {
//   return (length + 1) * (length) / 2;
// }

// function main() {
//   const testQuan = +readLine();
//   for (let testIx = 0; testIx < testQuan; testIx++) {
//     const inputStr = readLine();
//     const inputPattern = readLine();
//     let entryBorders = [];
//     let counter = 0;

//     for (let startIx = 0; startIx + inputPattern.length <= inputStr.length; startIx++) {
//       if ( inputStr.slice(startIx, startIx + inputPattern.length).includes(inputPattern) ) {
//         entryBorders.push([startIx, startIx + inputPattern.length - 1]);
//       }
//     }

//     entryBorders.push([inputStr.length, inputStr.length]);
//     let lastLeftBorder = 0;
//     for (let pairIx = 0; pairIx < entryBorders.length; pairIx++) {
//       let curPair = entryBorders[pairIx];
//       let curSubstrLen = curPair[1] - lastLeftBorder;
//       counter += getSubstrQuan(curSubstrLen);
//       lastLeftBorder = curPair[0] + 1;

//       if (curPair[1] - curPair[0] - 1 > 0) {
//         counter -= getSubstrQuan(curPair[1] - curPair[0] - 1);
//       }
//     }

//     console.log(counter);
//   }
// }

// Codeforces Round #698 (Div. 2) -> Problem A

// function main() {
//   let testQuan = +readLine();
//   for (let testIx = 0; testIx < testQuan; testIx++) {
//     let n = +readLine();
//     let a = readLine().split(" ");
//     a = a.map(item => +item);
//     let counterArr = [];
//     for (let i = 0; i <= n; i++) counterArr[i] = 0;

//     for (let el of a) {
//       counterArr[el]++;
//     }

//     console.log(Math.max(...counterArr));
//   }
// }

// .. -> Problem B

function main() {
  let testQuan = +readLine();
  for (let testIx = 0; testIx < testQuan; testIx++) {
    let [d, q] = readLine().split(" ").map(item => +item);
    let a = readLine().split(" ").map(item => +item);
    let possibleLastDigits = [];

    for (let multiplier = 1; multiplier < 11; multiplier++) {
      possibleLastDigits.push(multiplier * q % 10);
    }

    for (let el of a) {
      let curLastDigit = el % 10;

      if (q % 2 === 0 && el % 2 === 1) {
        el -= q * 10 + curLastDigit;

        if (el < 0) {
          console.log("NO");
          continue;
        }
      }

      curLastDigit = el % 10;
      let luckyNumsQuan = possibleLastDigits.indexOf(curLastDigit) + 1;

      if ( !possibleLastDigits.includes(curLastDigit) || luckyNumsQuan === -1 || luckyNumsQuan * q > el ) {
        console.log("NO");
        continue;
      }

      console.log("YES");
    }
  }
}

// .. -> Problem C

// function main() {

// }

process.stdin.resume();
process.stdin.setEncoding("utf8");
let standardInputString = "";
let curLine = 0;

function readLine() {
  return standardInputString[curLine++];
}

process.stdin.on("data", rawData => {
  standardInputString += rawData;
});

process.stdin.on("end", _ => {
  standardInputString = standardInputString
    .trim()
    .split("\n")
    .map(line => {
      return line.trim();
    });

  main();
});

// Pilot course from ITMO -> Z-function -> Step 1 -> Problem A

// function main() {
//   const testQuantity = +readLine();
//   for (let testNumber = 0; testNumber < testQuantity; testNumber++) {
//     let inputString = readLine();
//     let curLen = 0;
//     let curPrefix = "";
//     let maxPrefixLen = 0;

// .. -> Problem B

function main() {
  let testQuan = +readLine();
  for (let testIx = 0; testIx < testQuan; testIx++) {
    let [d, q] = readLine().split(" ").map(item => +item);
    let a = readLine().split(" ").map(item => +item);
    let possibleLastDigits = [];

    for (let multiplier = 1; multiplier < 11; multiplier++) {
      possibleLastDigits.push(multiplier * q % 10);
    }

    for (let el of a) {
      let curLastDigit = el % 10;
      let luckyNumsQuan = possibleLastDigits.indexOf(curLastDigit) + 1;

      if ( !possibleLastDigits.includes(curLastDigit) || luckyNumsQuan === -1 || luckyNumsQuan * q > el ) {
        console.log("NO");
        continue;
      }

      console.log("YES");
    }
  }
}

'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++];
}
/**
2
3 7
24 25 27
10 7
51 52 53 54 55 56 57 58 59 60
**/

function gcd(a, b) {
    if (!b) {
        return a;
    }

    return gcd(b, a % b);
};

function lcm(a, b) {
    return (a / gcd(a, b) * b);
}

function main() {
    let n = Number(readline());

    for(let r=0;r<n;r++) {
        solve();
    }

}

function solve() {
    let [q, d] = readline().split(" ");
    let a = readline().split(" ");

    let map = {};

    for(let i=0;i<a.length;i++) {
        if(a[i].includes(d)) {
            console.log('Yes');
        } else {
            let number = Number(d);
            let current = Number(a[i]);
            let found = false;
            while(!found && current > number) {
                current = current - number;

                if(map[current]) {
                    console.log(map[current]);
                    found = true;
                }

                if (("" + current).includes(d)) {
                    map[current] = 'Yes';
                    console.log(map[current]);
                    found = true;
                }
            }

            if(found === false) {
                map[a[i]] = 'No';
                console.log("No");
            }
        }
    }

}

"use strict"

let iter = parseInt(readline());

while(iter--){
    let temp = readline().split(" ").map(x => parseInt(x));
    let length = temp[0];
    let d = temp[1];
    let input = readline().split(" ");

    let obj = {
        "0" : null,
        "1" : null,
        "2" : null,
        "3" : null,
        "4" : null,
        "5" : null,
        "6" : null,
        "7" : null,
        "8" : null,
        "9" : null,
    };

    for(let i = 1; i < 11; i++){
        let t = String(i * d)
        if(obj[t[t.length - 1]] === null){
            obj[t[t.length - 1]] = parseInt(t);
        }
    }

    for(let i = 0; i < length; i++){
        let t = input[i][input[i].length - 1];
        if(obj[t] === null){
            let a = input[i] % (d * 10);
            let b = Math.trunc(input[i] / (d * 10))
            if(a % b === 0){
                print("YES");
            } else {
                print("NO")
            }
        } else if(obj[t] <= parseInt(input[i])){
            print("YES")
        } else {
            print("NO")
        }
    }
}

"use strict"

let iter = parseInt(readline());

while(iter--){
    let temp = readline().split(" ").map(x => parseInt(x));
    let length = temp[0];
    let d = temp[1];
    let input = readline().split(" ");

    let obj = {
        "0" : null,
        "1" : null,
        "2" : null,
        "3" : null,
        "4" : null,
        "5" : null,
        "6" : null,
        "7" : null,
        "8" : null,
        "9" : null,
    };

    for(let i = 1; i < 11; i++){
        let t = String(i * d)
        if(obj[t[t.length - 1]] === null){
            obj[t[t.length - 1]] = parseInt(t);
        }
    }

    for(let i = 0; i < length; i++){
        let t = input[i][input[i].length - 1];
        if(obj[t] === null){
            let a = input[i] % (d * 10);
            let b = Math.trunc(input[i] / (d * 10))
            if(a < b * 9){
                print("YES");
            } else {
                print("NO")
            }
        } else if(obj[t] <= parseInt(input[i])){
            print("YES")
        } else {
            print("NO")
        }
    }
}

"use strict"

let iter = parseInt(readline());

while(iter--){
    let temp = readline().split(" ").map(x => parseInt(x));
    let length = temp[0];
    let d = temp[1];
    let input = readline().split(" ");

    let obj = {
        "0" : null,
        "1" : null,
        "2" : null,
        "3" : null,
        "4" : null,
        "5" : null,
        "6" : null,
        "7" : null,
        "8" : null,
        "9" : null,
    };

    for(let i = 1; i < 11; i++){
        let t = String(i * d)
        if(obj[t[t.length - 1]] === null){
            obj[t[t.length - 1]] = parseInt(t);
        }
    }

    for(let i = 0; i < length; i++){
        let t = input[i][input[i].length - 1];
        if(obj[t] !== null && obj[t] <= parseInt(input[i])){
            print("YES")
        } else {
            print("NO")
        }
    }
}


You are given an array $$$a$$$ consisting of $$$n$$$ distinct positive integers.Let's consider an infinite integer set $$$S$$$ which contains all integers $$$x$$$ that satisfy at least one of the following conditions: $$$x = a_i$$$ for some $$$1 \leq i \leq n$$$. $$$x = 2y + 1$$$ and $$$y$$$ is in $$$S$$$. $$$x = 4y$$$ and $$$y$$$ is in $$$S$$$.For example, if $$$a = [1,2]$$$ then the $$$10$$$ smallest elements in $$$S$$$ will be $$$\{1,2,3,4,5,7,8,9,11,12\}$$$.Find the number of elements in $$$S$$$ that are strictly smaller than $$$2^p$$$. Since this number may be too large, print it modulo $$$10^9 + 7$$$.

The first line contains two integers $$$n$$$ and $$$p$$$ $$$(1 \leq n, p \leq 2 \cdot 10^5)$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ $$$(1 \leq a_i \leq 10^9)$$$. It is guaranteed that all the numbers in $$$a$$$ are distinct.

Print a single integer, the number of elements in $$$S$$$ that are strictly smaller than $$$2^p$$$. Remember to print it modulo $$$10^9 + 7$$$.

'use strict';

function solve(n, m, a) {
  a.sort((a, b) => a - b);
  const nums = [];
  const set = new Set();
  next: for (let num of a) {
    let t = num;
    while (t && (t & 1 || !(t & 3))) {
      if (set.has(t)) continue next;
      if (t & 1) {
        t >>= 1;
      } else {
        t >>= 2;
      }
    }
    if (set.has(t)) continue;
    nums.push(num);
    set.add(num);
  }
  const dp = new Array(m).fill(0);
  for (let num of nums) {
    let ans = 0;
    while (num) {
      ans++;
      num >>= 1;
    }
    dp[ans - 1]++;
  }
  let res = 0;
  for (let i = 0; i < m; i++) {
    var _dp, _dp2;
    dp[i] = mod(dp[i] + ((_dp = dp[i - 1]) !== null && _dp !== void 0 ? _dp : 0) + ((_dp2 = dp[i - 2]) !== null && _dp2 !== void 0 ? _dp2 : 0));
    res = mod(res + dp[i]);
  }
  return res;
}
const MOD = 10 ** 9 + 7;
function mod(num) {
  return (num % MOD + MOD) % MOD;
}

async function main(read) {
  try {
    let t = 1;
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const [n, m] = (await read()).split(' ').map(Number);
      const a = (await read()).split(' ').map(Number);
      res[i] = solve(n, m, a);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

let inputs,
    str = '';
function read() {
  return inputs.next().value.trim();
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});

'use strict';

function solve(n, m, a) {
  a.sort((a, b) => a - b);
  const nums = [];
  const set = new Set();
  next: for (let num of a) {
    let t = num;
    while (t && (t & 1 || !(t & 3))) {
      if (set.has(t)) continue next;
      if (t & 1) {
        t >>= 1;
      } else {
        t >>= 2;
      }
    }
    nums.push(num);
    set.add(num);
  }
  const dp = new Array(m).fill(0);
  for (let num of nums) {
    let ans = 0;
    while (num) {
      ans++;
      num >>= 1;
    }
    dp[ans - 1]++;
  }
  let res = 0;
  for (let i = 0; i < m; i++) {
    var _dp, _dp2;
    dp[i] = mod(dp[i] + ((_dp = dp[i - 1]) !== null && _dp !== void 0 ? _dp : 0) + ((_dp2 = dp[i - 2]) !== null && _dp2 !== void 0 ? _dp2 : 0));
    res = mod(res + dp[i]);
  }
  return res;
}
const MOD = 10 ** 9 + 7;
function mod(num) {
  return (num % MOD + MOD) % MOD;
}

async function main(read) {
  try {
    let t = 1;
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const [n, m] = (await read()).split(' ').map(Number);
      const a = (await read()).split(' ').map(Number);
      res[i] = solve(n, m, a);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

let inputs,
    str = '';
function read() {
  return inputs.next().value.trim();
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});

'use strict';

function solve(n, m, a) {
  a.sort((a, b) => a - b);
  const nums = [];
  const set = new Set();
  for (let num of a) {
    let t = num;
    while (t && (t & 1 || !(t & 3))) {
      if (t & 1) {
        t >>= 1;
      } else {
        t >>= 2;
      }
    }
    if (!set.has(t)) {
      nums.push(num);
      set.add(t);
    }
  }
  const dp = new Array(m).fill(0);
  for (let num of nums) {
    let ans = 0;
    while (num) {
      ans++;
      num >>= 1;
    }
    dp[ans - 1]++;
  }
  let res = 0;
  for (let i = 0; i < m; i++) {
    var _dp, _dp2;
    dp[i] = mod(dp[i] + ((_dp = dp[i - 1]) !== null && _dp !== void 0 ? _dp : 0) + ((_dp2 = dp[i - 2]) !== null && _dp2 !== void 0 ? _dp2 : 0));
    res = mod(res + dp[i]);
  }
  return res;
}
const MOD = 10 ** 9 + 7;
function mod(num) {
  return (num % MOD + MOD) % MOD;
}

async function main(read) {
  try {
    let t = 1;
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const [n, m] = (await read()).split(' ').map(Number);
      const a = (await read()).split(' ').map(Number);
      res[i] = solve(n, m, a);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

let inputs,
    str = '';
function read() {
  return inputs.next().value.trim();
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});

'use strict';

function solve(n, m, a) {
  a.sort((a, b) => a - b);
  const nums = [];
  const set = new Set();
  for (let num of a) {
    let t = num;
    while (t && (t & 1 || t % 4 === 0)) {
      if (t & 1) {
        t++;
        while (!(t & 1)) {
          t >>= 1;
        }
        t--;
      } else {
        while (t % 4 === 0) t /= 4;
      }
    }
    if (!set.has(t)) {
      nums.push(num);
      set.add(t);
    }
  }
  const dp = new Array(m).fill(0);
  for (let num of nums) {
    let ans = 0;
    while (num) {
      ans++;
      num >>= 1;
    }
    dp[ans - 1]++;
  }
  let res = 0;
  for (let i = 0; i < m; i++) {
    var _dp, _dp2;
    dp[i] = mod(dp[i] + ((_dp = dp[i - 1]) !== null && _dp !== void 0 ? _dp : 0) + ((_dp2 = dp[i - 2]) !== null && _dp2 !== void 0 ? _dp2 : 0));
    res = mod(res + dp[i]);
  }
  return res;
}
const MOD = 10 ** 9 + 7;
function mod(num) {
  return (num % MOD + MOD) % MOD;
}

async function main(read) {
  try {
    let t = 1;
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const [n, m] = (await read()).split(' ').map(Number);
      const a = (await read()).split(' ').map(Number);
      res[i] = solve(n, m, a);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

let inputs,
    str = '';
function read() {
  return inputs.next().value.trim();
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});

'use strict';

function solve(n, m, a) {
  a.sort((a, b) => a - b);
  const nums = [];
  const set = new Set();
  for (let num of a) {
    let t = num;
    while (t > 1 && (t & 1 || t % 4 === 0)) {
      if (t & 1) {
        t++;
        while (!(t & 1)) {
          t >>= 1;
        }
        t--;
      } else {
        while (t % 4 === 0) t /= 4;
      }
    }
    if (!set.has(t)) {
      nums.push(num);
      set.add(t);
    }
  }
  const dp = new Array(m).fill(0);
  for (let num of nums) {
    let ans = 0;
    while (num) {
      ans++;
      num >>= 1;
    }
    dp[ans - 1]++;
  }
  let res = 0;
  for (let i = 0; i < m; i++) {
    var _dp, _dp2;
    dp[i] = mod(dp[i] + ((_dp = dp[i - 1]) !== null && _dp !== void 0 ? _dp : 0) + ((_dp2 = dp[i - 2]) !== null && _dp2 !== void 0 ? _dp2 : 0));
    res = mod(res + dp[i]);
  }
  return res;
}
const MOD = 10 ** 9 + 7;
function mod(num) {
  return (num % MOD + MOD) % MOD;
}

async function main(read) {
  try {
    let t = 1;
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const [n, m] = (await read()).split(' ').map(Number);
      const a = (await read()).split(' ').map(Number);
      res[i] = solve(n, m, a);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

let inputs,
    str = '';
function read() {
  return inputs.next().value.trim();
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});

'use strict';

function solve(n, m, a) {
  a.sort((a, b) => a - b);
  const nums = [];
  const set = new Set();
  for (let num of a) {
    let t = num;
    while (t > 1 && (t & 1 || t % 4 === 0)) {
      if (t & 1) {
        t++;
        while (!(t & 1)) {
          t >>= 1;
        }
        t--;
      } else {
        while (t % 4 === 0) t /= 4;
      }
    }
    if (!set.has(t)) {
      nums.push(num);
      set.add(t);
    }
  }
  const dp = new Array(m + 2).fill(0);
  for (let num of nums) {
    let ans = 0;
    while (num) {
      ans++;
      num >>= 1;
    }
    if (ans >= m) continue;
    dp[ans - 1]++;
  }
  let res = 0;
  for (let i = 0; i < m; i++) {
    var _dp, _dp2;
    dp[i] = mod(dp[i] + ((_dp = dp[i - 1]) !== null && _dp !== void 0 ? _dp : 0) + ((_dp2 = dp[i - 2]) !== null && _dp2 !== void 0 ? _dp2 : 0));
    res = mod(res + dp[i]);
  }
  return res;
}
const MOD = 10 ** 9 + 7;
function mod(num) {
  return (num % MOD + MOD) % MOD;
}

async function main(read) {
  try {
    let t = 1;
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const [n, m] = (await read()).split(' ').map(Number);
      const a = (await read()).split(' ').map(Number);
      res[i] = solve(n, m, a);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

let inputs,
    str = '';
function read() {
  return inputs.next().value.trim();
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});

'use strict';

function solve(n, m, a) {
  a.sort((a, b) => a - b);
  const nums = [];
  const odd = new Set(),
        even = new Set();
  for (let num of a) {
    if (num & 1) {
      let t = num + 1;
      while (!(t & 1)) {
        t >>= 1;
      }
      t--;
      if (!odd.has(t)) {
        nums.push(num);
        odd.add(t);
      }
      even.add(num);
    } else {
      odd.add(num);
      let t = num;
      while (t % 4 === 0) t /= 4;
      if (!even.has(t)) {
        nums.push(num);
        even.add(t);
      }
    }
  }
  const dp = new Array(m + 2).fill(0);
  for (let num of nums) {
    let ans = 0;
    while (num) {
      ans++;
      num >>= 1;
    }
    if (ans >= m) continue;
    dp[ans - 1]++;
  }
  let res = 0;
  for (let i = 0; i < m; i++) {
    var _dp, _dp2;
    dp[i] = mod(dp[i] + ((_dp = dp[i - 1]) !== null && _dp !== void 0 ? _dp : 0) + ((_dp2 = dp[i - 2]) !== null && _dp2 !== void 0 ? _dp2 : 0));
    res = mod(res + dp[i]);
  }
  return res;
}
const MOD = 10 ** 9 + 7;
function mod(num) {
  return (num % MOD + MOD) % MOD;
}

async function main(read) {
  try {
    let t = 1;
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const [n, m] = (await read()).split(' ').map(Number);
      const a = (await read()).split(' ').map(Number);
      res[i] = solve(n, m, a);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

let inputs,
    str = '';
function read() {
  return inputs.next().value.trim();
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});


You are given a directed graph $$$G$$$ which can contain loops (edges from a vertex to itself). Multi-edges are absent in $$$G$$$ which means that for all ordered pairs $$$(u, v)$$$ exists at most one edge from $$$u$$$ to $$$v$$$. Vertices are numbered from $$$1$$$ to $$$n$$$.A path from $$$u$$$ to $$$v$$$ is a sequence of edges such that:  vertex $$$u$$$ is the start of the first edge in the path;  vertex $$$v$$$ is the end of the last edge in the path;  for all pairs of adjacent edges next edge starts at the vertex that the previous edge ends on. We will assume that the empty sequence of edges is a path from $$$u$$$ to $$$u$$$.For each vertex $$$v$$$ output one of four values:  $$$0$$$, if there are no paths from $$$1$$$ to $$$v$$$;  $$$1$$$, if there is only one path from $$$1$$$ to $$$v$$$;  $$$2$$$, if there is more than one path from $$$1$$$ to $$$v$$$ and the number of paths is finite;  $$$-1$$$, if the number of paths from $$$1$$$ to $$$v$$$ is infinite. Let's look at the example shown in the figure.  Then:  the answer for vertex $$$1$$$ is $$$1$$$: there is only one path from $$$1$$$ to $$$1$$$ (path with length $$$0$$$);  the answer for vertex $$$2$$$ is $$$0$$$: there are no paths from $$$1$$$ to $$$2$$$;  the answer for vertex $$$3$$$ is $$$1$$$: there is only one path from $$$1$$$ to $$$3$$$ (it is the edge $$$(1, 3)$$$);  the answer for vertex $$$4$$$ is $$$2$$$: there are more than one paths from $$$1$$$ to $$$4$$$ and the number of paths are finite (two paths: $$$[(1, 3), (3, 4)]$$$ and $$$[(1, 4)]$$$);  the answer for vertex $$$5$$$ is $$$-1$$$: the number of paths from $$$1$$$ to $$$5$$$ is infinite (the loop can be used in a path many times);  the answer for vertex $$$6$$$ is $$$-1$$$: the number of paths from $$$1$$$ to $$$6$$$ is infinite (the loop can be used in a path many times).

The first contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Before each test case, there is an empty line. The first line of the test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 4 \cdot 10^5, 0 \le m \le 4 \cdot 10^5$$$) — numbers of vertices and edges in graph respectively. The next $$$m$$$ lines contain edges descriptions. Each line contains two integers $$$a_i$$$, $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$) — the start and the end of the $$$i$$$-th edge. The vertices of the graph are numbered from $$$1$$$ to $$$n$$$. The given graph can contain loops (it is possible that $$$a_i = b_i$$$), but cannot contain multi-edges (it is not possible that $$$a_i = a_j$$$ and $$$b_i = b_j$$$ for $$$i \ne j$$$). The sum of $$$n$$$ over all test cases does not exceed $$$4 \cdot 10^5$$$. Similarly, the sum of $$$m$$$ over all test cases does not exceed $$$4 \cdot 10^5$$$.

Output $$$t$$$ lines. The $$$i$$$-th line should contain an answer for the $$$i$$$-th test case: a sequence of $$$n$$$ integers from $$$-1$$$ to $$$2$$$.

var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    var l = 0;
    var t = +lines[l++]
    for (var i = 0; i < t; i++) {
        l++
        var [n, m] = lines[l++].trim().split(' ').map(Number)
        var arr = lines.slice(l, l + m).map(str => str.trim().split(' ').map(Number))
        l += m
        console.log(solve(n, m, arr))
    }
});

function solve(n, m, arr) {
    const adj = {}
    arr.forEach(([a, b]) => {
        adj[a] = adj[a] || []
        adj[a].push(b)
    })

    const color = {}
    const group = [null, [], []] // x, gray, black
    dfs1(adj, 1, color, group)

    const set1 = {}
    const set2 = {}
    group[1].forEach(u => {
        dfs2(adj, u, set1)
    })
    group[2].forEach(u => {
        dfs2(adj, u, set2)
    })
// console.log(group, set1, set2)
    const ans = []
    for (let i = 1; i <= n; i++) {
        let x = 0
        if (color[i]) {
            x = 1
            if (set1[i]) x = -1
            else if (set2[i]) x = 2
        }
        ans.push(x)
    }
    return ans.join(' ')
}

function dfs1(adj, r, color, group) {
    const stack = [[r, 0]]
    while (stack.length) {
        const [u, i] = stack[stack.length - 1]
        color[u] = 1

        const nb = adj[u] || []
        if (i < nb.length) {
            stack[stack.length - 1][1]++
            const v = nb[i]
            if (!color[v]) {
                stack.push([v, 0])
            } else if (group) {
                group[color[v]].push(v)
            }
        } else {
            stack.pop()
            color[u] = 2
        }
    }
}
function dfs2(adj, r, visited) {
    const stack = [[r, 0]]
    while (stack.length) {
        const [u, i] = stack[stack.length - 1]
        visited[u] = 1

        const nb = adj[u] || []
        if (i < nb.length) {
            stack[stack.length - 1][1]++
            const v = nb[i]
            if (!visited[v]) {
                stack.push([v, 0])
            }
        } else {
            stack.pop()
        }
    }
}