Algorithm Speedup

No attempts yetTime limit8sMemory limit128 MB

Problem

As a punishment for misbehaving, Byteasar must evaluate a mysterious Boolean-valued function F(x,y)F(x, y), defined for a pair of positive-integer sequences x=(x1,,xn)x = (x_1, \dots, x_n) and y=(y1,,ym)y = (y_1, \dots, y_m) as follows:

boolean F(x, y)
    if W(x) != W(y):              return 0
    else if |W(x)| = |W(y)| = 1:  return 1
    else:                         return F(p(x), p(y)) AND F(s(x), s(y))

Here:

  • W(x)W(x) is the set of values that occur in the sequence xx (the order and repetitions of elements do not matter).
  • p(x)p(x) is the longest prefix (an initial segment of any length) of xx such that W(p(x))W(x)W(p(x)) \neq W(x).
  • s(x)s(x) is the longest suffix (a final segment of any length) of xx such that W(s(x))W(x)W(s(x)) \neq W(x).
  • \land denotes logical conjunction, 11 is true, 00 is false, and z|z| is the number of elements of the set zz.

For example, for x=(2,3,7,2,7,4,7,2,4)x = (2, 3, 7, 2, 7, 4, 7, 2, 4) we have W(x)={2,3,4,7}W(x) = \{2, 3, 4, 7\}, p(x)=(2,3,7,2,7)p(x) = (2, 3, 7, 2, 7), and s(x)=(7,2,7,4,7,2,4)s(x) = (7, 2, 7, 4, 7, 2, 4).

Evaluating FF straight from its definition is hopelessly slow on large inputs, so you must compute it as fast as possible. Read several pairs of sequences (x,y)(x, y) and print the value of F(x,y)F(x, y) for each pair.

Input

The first line contains one integer kk (1k131 \le k \le 13), the number of sequence pairs to analyse. The pairs follow on the next 3k3k lines. For each pair, the first line holds two integers nn and mm (1n,m100,0001 \le n, m \le 100{,}000), the lengths of xx and yy. The second line holds the nn integers xix_i (1xi1001 \le x_i \le 100) forming xx, and the third line holds the mm integers yiy_i (1yi1001 \le y_i \le 100) forming yy, each separated by single spaces.

Output

Print exactly kk lines. The ii-th line (1ik1 \le i \le k) contains a single integer, 00 or 11, equal to the value of F(x,y)F(x, y) for the ii-th pair.