import std.conv, std.functional, std.range, std.stdio, std.string; import std.algorithm, std.array, std.bigint, std.bitmanip, std.complex, std.container, std.math, std.mathspecial, std.numeric, std.regex, std.typecons; import core.bitop; class EOFException : Throwable { this() { super("EOF"); } } string[] tokens; string readToken() { for (; tokens.empty; ) { if (stdin.eof) { throw new EOFException; } tokens = readln.split; } auto token = tokens.front; tokens.popFront; return token; } int readInt() { return readToken.to!int; } long readLong() { return readToken.to!long; } string COLOR(string s = "") { return "\x1b[" ~ s ~ "m"; } bool chmin(T)(ref T t, in T f) { if (t > f) { t = f; return true; } else { return false; } } bool chmax(T)(ref T t, in T f) { if (t < f) { t = f; return true; } else { return false; } } int binarySearch(alias pred, T)(in T[] as) { int lo = -1, hi = cast(int)(as.length); for (; lo + 1 < hi; ) { const mid = (lo + hi) >> 1; (unaryFun!pred(as[mid]) ? hi : lo) = mid; } return hi; } int lowerBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a >= val)); } int upperBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a > val)); } enum E = 30; enum INF = 10L^^9; void main() { try { for (; ; ) { const numCases = readInt; foreach (caseId; 0 .. numCases) { const M = readInt; const N = readInt; auto B = new int[M]; foreach (x; 0 .. M) B[x] = readInt; auto C = new int[N]; foreach (y; 0 .. N) C[y] = readInt; auto A = new int[][](M, N); foreach (x; 0 .. M) foreach (y; 0 .. N) A[x][y] = readInt; bool ok = true; foreach (x; 0 .. M) foreach (y; 0 .. N) { ok = ok && !(A[0][0] ^ A[0][y] ^ A[x][0] ^ A[x][y]); } long ans = INF; if (ok) { auto bs = new int[M]; auto cs = new int[N]; foreach (y; 0 .. N) cs[y] = A[0][y] ^ bs[0]; foreach (x; 1 .. M) bs[x] = A[x][0] ^ cs[0]; debug { writeln("bs = ", bs, ", cs = ", cs); } alias Entry = Tuple!(int, "key", int, "val"); Entry[] es; void add(int l, int r, int val) { es ~= Entry(l, +val); es ~= Entry(r, -val); } add(0, 1 << E, 0); void check(int D, int d) { debug { writeln("check ", D, " ", d); } const e0 = D ? (bsr(D) + 1) : 0; int l = (d >> e0) << e0; int r = l + (1 << e0); add(0, l, INF); add(r, 1 << E, INF); foreach_reverse (e; 0 .. e0) { const mid = (l + r) >> 1; if (D >> e & 1) { if (d >> e & 1) { add(mid, r, 1); r = mid; } else { add(l, mid, 1); l = mid; } } else { if (d >> e & 1) { add(l, mid, 2); l = mid; } else { add(mid, r, 2); r = mid; } } } add(l, r, 1); add(d, d + 1, -1); } foreach (x; 0 .. M) check(B[x], bs[x]); foreach (y; 0 .. N) check(C[y], cs[y]); es.sort; const esLen = cast(int)(es.length); long now; foreach (j; 0 .. esLen - 1) { now += es[j].val; if (es[j].key < es[j + 1].key) { debug { writefln("[%s, %s): %s", es[j].key, es[j + 1].key, now); } chmin(ans, now); } } } writeln((ans < INF) ? ans : -1); } } } catch (EOFException e) { } }