using System;

namespace kvalifikacije
{
    class Program
    {
        static void Main(string[] args)
        {
            int t = int.Parse(Console.ReadLine());
            int[] end = new int[t];
            for (int i = 0; i < t; i++)
            {
                string[] niz = Console.ReadLine().Split();
                int n = Int32.Parse(niz[0]);
                int m = Int32.Parse(niz[1]);
                int[] a = new int[n];
                string[] niz2 = Console.ReadLine().Split();
                for (int j = 0; j < n; j++)
                {
                    a[j] = (int)Int64.Parse(niz2[j]);
                }
                int[] b = new int[m];
                string[] niz3 = Console.ReadLine().Split();
                for (int j = 0; j < m; j++)
                {
                    b[j] = (int)Int64.Parse(niz3[j]);
                }
                int x = a[0] % 3;
                int br1 = 0;
                int br2 = 0;
                for (int j = 1; j < n; j++)
                {
                    if (a[j] % 3 != x)
                        br1++;
                    if (j<m && b[j] % 3 == x)
                        br2++;
                }
                if (br1 == 0 && br2 == 0)
                    end[i] = 1;
                else
                    end[i] = 0;
            }
            for (int i = 0; i < t; i++)
            {
                Console.WriteLine(end[i]);
            }
        }
    }
}