#include #ifdef LOCAL #include #else #define debug(...) void(0) #endif using namespace std; typedef long long ll; #define all(x) begin(x), end(x) constexpr int INF = (1 << 30) - 1; constexpr long long IINF = (1LL << 60) - 1; constexpr int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1}; template istream& operator>>(istream& is, vector& v) { for (auto& x : v) is >> x; return is; } template ostream& operator<<(ostream& os, const vector& v) { auto sep = ""; for (const auto& x : v) os << exchange(sep, " ") << x; return os; } template bool chmin(T& x, U&& y) { return y < x and (x = forward(y), true); } template bool chmax(T& x, U&& y) { return x < y and (x = forward(y), true); } template void mkuni(vector& v) { sort(begin(v), end(v)); v.erase(unique(begin(v), end(v)), end(v)); } template int lwb(const vector& v, const T& x) { return lower_bound(begin(v), end(v), x) - begin(v); } int topbit(signed t) { return t == 0 ? -1 : 31 - __builtin_clz(t); } const int MAX_LOG = 30; /* 上から桁ごとに考えて良い r, c のいずれか 1 つの値を決めると全て決まる r[0] を決めるとする r[0] ^ (a[0][0] ^ a[i][0]) = r[i] r[0] ^ a[0][i] = c[i] r[0] = r[i] ^ (a[0][0] ^ a[i][0]) r[0] = c[i] ^ a[0][i] a[i][j] = r[i] ^ c[j] = a[0][0] ^ a[i][0] ^ a[0][j] r[i] = r[0] ^ x が 0, R[i], 2^k より大きくなったらそれぞれ 1, 1, inf のコスト */ struct node { array nxt; ll w; node() : nxt{-1, -1}, w(0) {} }; void solve() { int n, m; cin >> n >> m; vector R(n), C(m); cin >> R >> C; vector a(n, vector(m)); cin >> a; vector b(n, vector(m)); vector r(n), c(m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (a[0][0] ^ a[i][0] ^ a[0][j] ^ a[i][j]) { cout << -1 << '\n'; return; } } } vector> cs; for (int i = 0; i < n; i++) { int x = a[0][0] ^ a[i][0]; if (R[i] == 0) cs.emplace_back(x, 0, INF); else { cs.emplace_back(x, 0, 1); cs.emplace_back(x, R[i], 1); cs.emplace_back(x, (1 << (topbit(R[i]) + 1)) - 1, INF); } } for (int j = 0; j < m; j++) { int x = a[0][j]; if (C[j] == 0) cs.emplace_back(x, 0, INF); else { cs.emplace_back(x, 0, 1); cs.emplace_back(x, C[j], 1); cs.emplace_back(x, (1 << (topbit(C[j]) + 1)) - 1, INF); } } vector nodes(1); auto add = [&](int x, int y, int z) { for (int i = MAX_LOG - 1, cur = 0; i >= 0; i--) { int f = x >> i & 1, g = y >> i & 1; for (int j = 0; j < 2; j++) { if (nodes[cur].nxt[j] == -1) { nodes[cur].nxt[j] = nodes.size(); nodes.emplace_back(); } } if (g == 0) { int ch = nodes[cur].nxt[f ^ g ^ 1]; nodes[ch].w += z; } cur = nodes[cur].nxt[f ^ g]; } }; for (auto [x, y, z] : cs) add(x, y, z); ll ans = INF; auto dfs = [&](auto self, int v, ll d) -> void { d += nodes[v].w; bool leaf = true; for (int i = 0; i < 2; i++) { if (nodes[v].nxt[i] == -1) continue; self(self, nodes[v].nxt[i], d); leaf = false; } if (leaf) ans = min(ans, d); }; dfs(dfs, 0, 0); cout << (ans == INF ? -1 : ans) << '\n'; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int T; cin >> T; for (; T--;) solve(); return 0; }