#include #include #include #include #include #include #include #include int KthBit(const int x, const int k) { return x >> k & 1; } // #895425 ベース // -1 ビット目を探索している。 template int Solve(const std::vector& z, const std::vector>& a) { const int n = a.size(), m = a.front().size(); assert(std::ssize(z) == n + m); std::vector y(n + m, 0); for (int i = 1; i < n; ++i) { y[i] = a[i].front() ^ a.front().front(); } for (int j = 0; j < m; ++j) { y[j + n] = a.front()[j]; } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if ((y[i] ^ y[j + n]) != a[i][j]) return -1; } } int min_fx = (n + m) * 2 + 1; const auto dfs = [&z, &y, &min_fx]( auto dfs, const int bit, const int fx, const std::vector& or_012, const std::vector& or_01, const std::vector& or_12) -> void { if (or_012.empty() && or_01.empty() && or_12.empty()) { // ここ min_fx = std::min(min_fx, fx); return; } for (const int x_bit : std::array{0, 1}) { bool is_valid = true; int next_fx = fx; std::vector next_or_012, next_or_01, next_or_12; for (const int i : or_012) { if (KthBit(y[i], bit) != x_bit) { if (KthBit(z[i], bit) == 0) { is_valid = false; break; } ++next_fx; next_or_12.emplace_back(i); } else { (KthBit(z[i], bit) == 1 ? next_or_01 : next_or_012).emplace_back(i); } } if (!is_valid) continue; for (const int i : or_01) { if (KthBit(y[i], bit) != x_bit) { ++next_fx; } else { next_or_01.emplace_back(i); } } for (const int i : or_12) { const int x_xor_y = (KthBit(y[i], bit) != x_bit ? 1 : 0); const int z_bit = KthBit(z[i], bit); if (x_xor_y > z_bit) { ++next_fx; } else if (x_xor_y == z_bit) { next_or_12.emplace_back(i); } } dfs(dfs, bit - 1, next_fx, next_or_012, next_or_01, next_or_12); } }; std::vector or_012(n + m); std::iota(or_012.begin(), or_012.end(), 0); dfs(dfs, D - 1, 0, or_012, std::vector{}, std::vector{}); return min_fx > (n + m) * 2 ? -1 : min_fx; } int main() { constexpr int kMaxT = 50000, kMaxNM = 50000, kDigits = 30; int t; std::cin >> t; assert(1 <= t && t <= kMaxT); while (t--) { int n, m; std::cin >> n >> m; assert(1 <= n && 1 <= m && n * m <= kMaxNM); std::vector z(n + m); for (int i = 0; i < n + m; ++i) { std::cin >> z[i]; assert(0 <= z[i] && z[i] < (1 << kDigits)); } std::vector a(n, std::vector(m, 0)); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { std::cin >> a[i][j]; assert(0 <= a[i][j] && a[i][j] < (1 << kDigits)); } } std::cout << Solve(z, a) << '\n'; } return 0; }