EXBANNERH - Editorial

PROBLEM LINK:

Practice
Contest: Division 1
Contest: Division 2
Contest: Division 3
Contest: Division 4

Author: am_aadvik
Tester: iceknight1093
Editorialist: iceknight1093

DIFFICULTY:

TBD

PREREQUISITES:

Inclusion-exclusion

PROBLEM:

You are given the row-wise and column-wise bitwise ANDs, ORs, and XORs of an N\times M grid.
Count the number of grids that satisfy these conditions, modulo 10^9 + 7.

Additional constraints: at least 4 rows and columns each, every bitwise AND is 0, every bitwise OR is 1, every bitwise XOR is in \{0, 1\}.

EXPLANATION:

From the easy version of the problem, we know that a solution exists if and only if the XOR of row XORs equals the XOR of column XORs.
So, we only proceed in such a case.

We saw that the AND/OR constraints only enforce that every row and every column must have both a 0 and a 1.
What if these constraints weren’t present, and we only had the XOR constraints to deal with?

Well, in that case the problem actually becomes trivial because we can do the following:

  • Consider the subgrid formed by the first N-1 rows and first M-1 columns.
  • For each cell in this (N-1)\times (M-1) grid, choose either 0 or 1 independently.
    There are thus
    2^{(N-1)\cdot (M-1)}
    choices for this subgrid.
  • After fixing all these cells, note that the remaining part of the grid is uniquely determined by the row and column XORs.
    Every element A_{i, M} for 1 \le i \lt M is forced by the XOR of the i-th row, and every element A_{N, i} for 1 \le i \lt N is forced by the XOR of the i-th column.
  • After filling in everything else, A_{N, M} is forced by the XOR of both its row and its column; but they will match because we ensured that the row and column XORs were globally compatible to start with.

So, if we didn’t have the AND/OR constraints, the answer is trivially 2^{(N-1)\cdot (M-1)}.

The question now is, what happens when we bring in these additional constraints?
To handle that, we’ll subtract out the “bad” cases, i.e. ones where some row and/or column is either all zeros or all ones.


First, for each row and each column, determine whether it can become “bad”, either via all zeros or all ones.
This depends on both its required XOR, as well as the parity of its length.

Note that it’s possible for a row/column to have both all ones and all zeros (for example, a row of even length with XOR 0.)

Let r_0, r_1, c_0, c_1 denote these counts.

We now try to consider a “bad” case: some rows and some columns have all-equal values.
Say, x rows and y columns have all-equal values.

For now, we’ll assume 1 \le x \lt N and 1 \le y \lt M, i.e. there is some intersection between fixed rows and columns; and also there are some cells whose values are not fixed.

Note that for this to happen, the chosen rows and columns must all have the same value; since they intersect.
If they are all to have the value 0,

  • There are \binom{r_0}{x} ways to choose the rows that can become 0, and \binom{c_0}{y} ways to choose the columns.
  • That leaves a grid of size (N-x) \times (M-y).
    As noted earlier, there are
    2^{(N-x-1)\cdot (M-y-1)}
    ways to fill in the remaining rows/columns, in such a way that all XOR constraints are satisfied.
  • The total number of ways is then obtained by multiplying all three together, i.e.
    \binom{r_0}{x}\binom{c_0}{y}2^{(N-x-1)\cdot (M-y-1)}

For all the rows/columns having value 1, the same computation applies, just use r_1 and c_1 instead.

Note, however, that when filling in the missing elements, we didn’t particularly care for ensuring that the non-chosen rows/columns are not filled by a single element.
This means that there could certainly be cases where more than x rows and/or more than y columns are fully filled, which are being counted here.

To get around this, we will use the inclusion-exclusion principle.
Working out the details, it can be seen that the multiplier is (-1)^{x+y}, i.e. if x+y is even then we add the count to the answer and otherwise we subtract it.


Now, earlier we only looked at the case where full rows and columns both exist.
However, there is also the case where only some rows are full, but no columns are.

This can similarly be handled using inclusion-exclusion, though there is one detail that is slightly different.

Looking at for example the rows, suppose we want k rows to be all-equal; and we’ve chosen a subset of k rows.
Then,

  • If M (the number of columns) is odd, then each chosen row has only one choice: either all 0 or all 1, depending on its XOR.
    So, there are r_0 + r_1 eligible rows, and we can pick any subset of them for \binom{r_0+r_1}{k} choices in total.
  • If M is even, then a row with XOR 1 can never have all its elements equal, while a row with XOR 0 can have either all zeros or all ones.
    So, r_0 = r_1 here and they represent the same set of rows, so there are \binom{r_0}{k} subsets of rows and then 2^k choices for which value each row takes.

After fixing this, do the usual computation of XOR-fixing the remaining grid (so with k rows fixed that’s 2^{(N-k-1)\cdot (M-1)}).
Then once again apply inclusion-exclusion on this.

The same thing can be done for fully-fixed columns but not rows.

Finally, there’s the case of all rows and/or all columns being fixed, but that’s only a couple of cases and so must be handled separately.
Note for example that all rows being fixed is only possible if all columns have the same required XOR, and vice versa.

Putting everything together gives the final answer.

TIME COMPLEXITY:

\mathcal{O}(NM) per testcase.

CODE:

Editorialist's code (C++)
// #pragma GCC optimize("O3,unroll-loops")
// #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
#include "bits/stdc++.h"
#include <cassert>
using namespace std;
using ll = long long int;
mt19937_64 RNG(chrono::high_resolution_clock::now().time_since_epoch().count());

/**
 * Integers modulo p, where p is a prime
 * Source: Aeren (modified from tourist?)
 *         Modmul for 64-bit mod from kactl:ModMulLL
 * Works with p < 7.2e18 with x87 80-bit long double, and p < 2^52 ~ 4.5e12 with 64-bit
 */
template<typename T>
struct Z_p{
	using Type = typename decay<decltype(T::value)>::type;
	static vector<Type> MOD_INV;
	constexpr Z_p(): value(){ }
	template<typename U> Z_p(const U &x){ value = normalize(x); }
	template<typename U> static Type normalize(const U &x){
		Type v;
		if(-mod() <= x && x < mod()) v = static_cast<Type>(x);
		else v = static_cast<Type>(x % mod());
		if(v < 0) v += mod();
		return v;
	}
	const Type& operator()() const{ return value; }
	template<typename U> explicit operator U() const{ return static_cast<U>(value); }
	constexpr static Type mod(){ return T::value; }
	Z_p &operator+=(const Z_p &otr){ if((value += otr.value) >= mod()) value -= mod(); return *this; }
	Z_p &operator-=(const Z_p &otr){ if((value -= otr.value) < 0) value += mod(); return *this; }
	template<typename U> Z_p &operator+=(const U &otr){ return *this += Z_p(otr); }
	template<typename U> Z_p &operator-=(const U &otr){ return *this -= Z_p(otr); }
	Z_p &operator++(){ return *this += 1; }
	Z_p &operator--(){ return *this -= 1; }
	Z_p operator++(int){ Z_p result(*this); *this += 1; return result; }
	Z_p operator--(int){ Z_p result(*this); *this -= 1; return result; }
	Z_p operator-() const{ return Z_p(-value); }
	template<typename U = T>
	typename enable_if<is_same<typename Z_p<U>::Type, int>::value, Z_p>::type &operator*=(const Z_p& rhs){
		#ifdef _WIN32
		uint64_t x = static_cast<int64_t>(value) * static_cast<int64_t>(rhs.value);
		uint32_t xh = static_cast<uint32_t>(x >> 32), xl = static_cast<uint32_t>(x), d, m;
		asm(
			"divl %4; \n\t"
			: "=a" (d), "=d" (m)
			: "d" (xh), "a" (xl), "r" (mod())
		);
		value = m;
		#else
		value = normalize(static_cast<int64_t>(value) * static_cast<int64_t>(rhs.value));
		#endif
		return *this;
	}
	template<typename U = T>
	typename enable_if<is_same<typename Z_p<U>::Type, int64_t>::value, Z_p>::type &operator*=(const Z_p &rhs){
		uint64_t ret = static_cast<uint64_t>(value) * static_cast<uint64_t>(rhs.value) - static_cast<uint64_t>(mod()) * static_cast<uint64_t>(1.L / static_cast<uint64_t>(mod()) * static_cast<uint64_t>(value) * static_cast<uint64_t>(rhs.value));
		value = normalize(static_cast<int64_t>(ret + static_cast<uint64_t>(mod()) * (ret < 0) - static_cast<uint64_t>(mod()) * (ret >= static_cast<uint64_t>(mod()))));
		return *this;
	}
	template<typename U = T>
	typename enable_if<!is_integral<typename Z_p<U>::Type>::value, Z_p>::type &operator*=(const Z_p &rhs){
		value = normalize(value * rhs.value);
		return *this;
	}
	template<typename U>
	Z_p &operator^=(U e){
		if(e < 0) *this = 1 / *this, e = -e;
		Z_p res = 1;
		for(; e; *this *= *this, e >>= 1) if(e & 1) res *= *this;
		return *this = res;
	}
	template<typename U>
	Z_p operator^(U e) const{
		return Z_p(*this) ^= e;
	}
	Z_p &operator/=(const Z_p &otr){
		Type a = otr.value, m = mod(), u = 0, v = 1;
		if(a < (int)MOD_INV.size()) return *this *= MOD_INV[a];
		while(a){
			Type t = m / a;
			m -= t * a; swap(a, m);
			u -= t * v; swap(u, v);
		}
		assert(m == 1);
		return *this *= u;
	}
	template<typename U> friend const Z_p<U> &abs(const Z_p<U> &v){ return v; }
	Type value;
};
template<typename T> bool operator==(const Z_p<T> &lhs, const Z_p<T> &rhs){ return lhs.value == rhs.value; }
template<typename T, typename U, typename enable_if<is_integral<U>::value>::type* = nullptr> bool operator==(const Z_p<T>& lhs, U rhs){ return lhs == Z_p<T>(rhs); }
template<typename T, typename U, typename enable_if<is_integral<U>::value>::type* = nullptr> bool operator==(U lhs, const Z_p<T> &rhs){ return Z_p<T>(lhs) == rhs; }
template<typename T> bool operator!=(const Z_p<T> &lhs, const Z_p<T> &rhs){ return !(lhs == rhs); }
template<typename T, typename U, typename enable_if<is_integral<U>::value>::type* = nullptr> bool operator!=(const Z_p<T> &lhs, U rhs){ return !(lhs == rhs); }
template<typename T, typename U, typename enable_if<is_integral<U>::value>::type* = nullptr> bool operator!=(U lhs, const Z_p<T> &rhs){ return !(lhs == rhs); }
template<typename T> bool operator<(const Z_p<T> &lhs, const Z_p<T> &rhs){ return lhs.value < rhs.value; }
template<typename T> bool operator>(const Z_p<T> &lhs, const Z_p<T> &rhs){ return lhs.value > rhs.value; }
template<typename T> bool operator<=(const Z_p<T> &lhs, const Z_p<T> &rhs){ return lhs.value <= rhs.value; }
template<typename T> bool operator>=(const Z_p<T> &lhs, const Z_p<T> &rhs){ return lhs.value >= rhs.value; }
template<typename T> Z_p<T> operator+(const Z_p<T> &lhs, const Z_p<T> &rhs){ return Z_p<T>(lhs) += rhs; }
template<typename T, typename U, typename enable_if<is_integral<U>::value>::type* = nullptr> Z_p<T> operator+(const Z_p<T> &lhs, U rhs){ return Z_p<T>(lhs) += rhs; }
template<typename T, typename U, typename enable_if<is_integral<U>::value>::type* = nullptr> Z_p<T> operator+(U lhs, const Z_p<T> &rhs){ return Z_p<T>(lhs) += rhs; }
template<typename T> Z_p<T> operator-(const Z_p<T> &lhs, const Z_p<T> &rhs){ return Z_p<T>(lhs) -= rhs; }
template<typename T, typename U, typename enable_if<is_integral<U>::value>::type* = nullptr> Z_p<T> operator-(const Z_p<T>& lhs, U rhs){ return Z_p<T>(lhs) -= rhs; }
template<typename T, typename U, typename enable_if<is_integral<U>::value>::type* = nullptr> Z_p<T> operator-(U lhs, const Z_p<T> &rhs){ return Z_p<T>(lhs) -= rhs; }
template<typename T> Z_p<T> operator*(const Z_p<T> &lhs, const Z_p<T> &rhs){ return Z_p<T>(lhs) *= rhs; }
template<typename T, typename U, typename enable_if<is_integral<U>::value>::type* = nullptr> Z_p<T> operator*(const Z_p<T>& lhs, U rhs){ return Z_p<T>(lhs) *= rhs; }
template<typename T, typename U, typename enable_if<is_integral<U>::value>::type* = nullptr> Z_p<T> operator*(U lhs, const Z_p<T> &rhs){ return Z_p<T>(lhs) *= rhs; }
template<typename T> Z_p<T> operator/(const Z_p<T> &lhs, const Z_p<T> &rhs) { return Z_p<T>(lhs) /= rhs; }
template<typename T, typename U, typename enable_if<is_integral<U>::value>::type* = nullptr> Z_p<T> operator/(const Z_p<T>& lhs, U rhs) { return Z_p<T>(lhs) /= rhs; }
template<typename T, typename U, typename enable_if<is_integral<U>::value>::type* = nullptr> Z_p<T> operator/(U lhs, const Z_p<T> &rhs) { return Z_p<T>(lhs) /= rhs; }
template<typename T> istream &operator>>(istream &in, Z_p<T> &number){
	typename common_type<typename Z_p<T>::Type, int64_t>::type x;
	in >> x;
	number.value = Z_p<T>::normalize(x);
	return in;
}
template<typename T> ostream &operator<<(ostream &out, const Z_p<T> &number){ return out << number(); }

/*
using ModType = int;
struct VarMod{ static ModType value; };
ModType VarMod::value;
ModType &mod = VarMod::value;
using Zp = Z_p<VarMod>;
*/

constexpr int mod = 1e9 + 7; // 1000000007
// constexpr int mod = (119 << 23) + 1; // 998244353
// constexpr int mod = 1e9 + 9; // 1000000009
using Zp = Z_p<integral_constant<decay<decltype(mod)>::type, mod>>;

template<typename T> vector<typename Z_p<T>::Type> Z_p<T>::MOD_INV;
template<typename T = integral_constant<decay<decltype(mod)>::type, mod>>
void precalc_inverse(int SZ){
	auto &inv = Z_p<T>::MOD_INV;
	if(inv.empty()) inv.assign(2, 1);
	for(; inv.size() <= SZ; ) inv.push_back((mod - 1LL * mod / (int)inv.size() * inv[mod % (int)inv.size()]) % mod);
}

template<typename T>
vector<T> precalc_power(T base, int SZ){
	vector<T> res(SZ + 1, 1);
	for(auto i = 1; i <= SZ; ++ i) res[i] = res[i - 1] * base;
	return res;
}

template<typename T>
vector<T> precalc_factorial(int SZ){
	vector<T> res(SZ + 1, 1); res[0] = 1;
	for(auto i = 1; i <= SZ; ++ i) res[i] = res[i - 1] * i;
	return res;
}

int main()
{
    ios::sync_with_stdio(false); cin.tie(0);

    auto fac = precalc_factorial<Zp>(200005);
    auto inv = fac;
    for (auto &x : inv) x = 1/x;
    auto C = [&] (int n, int r) {
        if (r < 0 or r > n) return Zp(0);
        return fac[n] * inv[r] * inv[n-r];
    };

    int t; cin >> t;
    while (t--) {
        int n, m; cin >> n >> m;
        vector<array<int, 3>> rows(n), cols(m);
        for (auto &[x, y, z] : rows) cin >> x >> y >> z;
        for (auto &[x, y, z] : cols) cin >> x >> y >> z;

        auto solve = [&] (auto rowinf, auto colinf) {
            int xorchk = 0;
            for (auto [x, o, a] : rowinf) xorchk ^= x;
            for (auto [x, o, a] : colinf) xorchk ^= x;
            if (xorchk) return Zp(0);

            // inc-exc on bad rows/columns
            Zp ways = Zp(2) ^ ((n-1) * (m-1));

            int r0 = 0, c0 = 0;
            int r1 = 0, c1 = 0;
            for (auto [x, o, a] : rowinf) {
                if (x == 0) {
                    if (m%2 == 0) ++r0, ++r1;
                    else ++r0;
                }
                else {
                    if (m%2 == 1) ++r1;
                }
            }
            for (auto [x, o, a] : colinf) {
                if (x == 0) {
                    if (n%2 == 0) ++c0, ++c1;
                    else ++c0;
                }
                else {
                    if (n%2 == 1) ++c1;
                }
            }

            // bad rows and bad columns
            for (int i = 1; i < n; ++i) for (int j = 1; j < m; ++j) {
                Zp rem = Zp(2) ^ ((n-i-1) * (m-j-1));
                Zp mul = (i+j)%2 == 0 ? 1 : -1;
                
                // make 0
                Zp cur = C(r0, i) * C(c0, j);
                ways += mul * cur * rem;

                // make 1
                cur = C(r1, i) * C(c1, j);
                ways += mul * cur * rem;
            }

            // bad rows only
            for (int i = 1; i < n; ++i) {
                Zp rem = Zp(2) ^ ((n-i-1) * (m-1));
                if (m%2 == 1) {
                    // separate
                    Zp cur = C(r0+r1, i);
                    Zp mul = (i%2 == 0) ? 1 : -1;
                    ways += cur*mul*rem;
                }
                else {
                    // two types for each valid row
                    Zp cur = C(r0, i) * (Zp(2) ^ i);
                    Zp mul = (i%2 == 0) ? 1 : -1;
                    ways += cur*mul*rem;
                }
            }

            // bad cols only
            for (int i = 1; i < m; ++i) {
                Zp rem = Zp(2) ^ ((n-1) * (m-i-1));
                if (n%2 == 1) {
                    // separate
                    Zp cur = C(c0+c1, i);
                    Zp mul = (i%2 == 0) ? 1 : -1;
                    ways += cur*mul*rem;
                }
                else {
                    // two types for each valid row
                    Zp cur = C(c0, i) * (Zp(2) ^ i);
                    Zp mul = (i%2 == 0) ? 1 : -1;
                    ways += cur*mul*rem;
                }
            }

            // all rows bad
            // possible iff all columns are the same
            if (c0 == 0 or c0 == m) {
                Zp here = 0;
                if (m%2 == 1) here = 1;
                else if (r0 == n) here = Zp(2) ^ (n-1);

                if (n%2 == 0) ways += here;
                else ways -= here;
            }

            // all cols bad, similar
            if (r0 == 0 or r0 == n) {
                Zp here = 0;
                if (n%2 == 1) here = 1;
                else if (c0 == m) here = Zp(2) ^ (m-1);

                if (m%2 == 0) ways += here;
                else ways -= here;
            }

            // all rows and all cols -> everything is constant
            if (r0 == n and c0 == m) {
                if (n%2 == 1) ways += 1;
                else ways -= 1;
                if (m%2 == 1) ways += 1;
                else ways -= 1;
                if ((n+m)%2 == 1) ways += 1;
                else ways -= 1;
            }
            if (r1 == n and c1 == m) {
                if (n%2 == 1) ways += 1;
                else ways -= 1;
                if (m%2 == 1) ways += 1;
                else ways -= 1;
                if ((n+m)%2 == 1) ways += 1;
                else ways -= 1;
            }
            return ways;
        };

        cout << solve(rows, cols) << '\n';
    }
}