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:
Sorting, bitwise operations
PROBLEM:
You are given the row-wise and column-wise bitwise ANDs, ORs, and XORs of an N\times M grid.
Reconstruct any grid that satisfies these conditions, if one exists.
EXPLANATION:
First, clearly we can solve for each bit independently; so we will fix a bit and henceforth assume all values are 0 or 1.
Notice that some information forces certain values:
- If a row/column has a bitwise AND of 1, then every value in that row/column must be 1.
- This also fixes the bitwise OR and XOR of the row/column, so make sure those are valid.
- If a row/column has a bitwise OR of 0, then every value in that row/column must be 0.
- Similarly, this fixes the bitwise AND and XOR of the row/column, so check validity.
Thus, certain cells of the grid are fixed.
Note that some cell might have its value fixed by both its row and by its column; in this case the values must match otherwise no solution exists.
Further, there’s a global parity condition (which we needed to check even in the easy version) - the XOR of all row XORs and the XOR of all column XORs must match, since they both represent the XOR of the whole grid.
We’ll proceed assuming there’s no mismatch so far.
For each row/column that’s not fully fixed so far, there are two constraints it needs to follow:
- It must contain both a 0 and a 1, and
- The parity of the number of ones in it is fixed (by its XOR.)
Luckily, there exists a way to handle this without much casework at all.
First, other than forced values, we’ll set everything in the grid to 0.
We’ll then try to place 1’s to satisfy the necessary conditions.
For each “free” (i.e. not fixed) row/column, we can compute both the minimum and the maximum number of ones it can contain.
Note that the minimum will always be among \{0, 1, 2\} depending on both its XOR parity and whether it already has a 1 placed there; and similarly the maximum will be among \{F, F-1, F-2\} where F is the number of unforced positions in it.
In particular, let’s define:
- RL_i and RU_i to be the lower and upper bounds on the number of ones present in the i-th row (assuming the i-th row isn’t forced), and
- CL_i and CU_i to be the lower and upper bounds on the number of ones present in the i-th column (assuming it isn’t forced, again)
Note that if RL_i \gt RU_i or CL_i \gt CU_i for any i, then no solution can exist; so we proceed assuming the ranges are valid.
From these bounds, we obtain further global lower/upper bounds: define
- x_R = \sum_i RL_i, the sum taken over only un-forced rows i.
- This is the minimum number of extra ones needed to satisfy every row.
- y_R = \sum_i RU_i, the sum taken over only un-forced rows i.
- This is the maximum number of extra ones possible while satisfying every row.
- x_C and y_C defined similarly but for columns.
Then, from the bounds, we surely need at least \max(x_R, x_C) ones in total; while also being able to use at most \min(y_R, y_C) of them.
So if \max(x_R, x_C) \gt \min(y_R, y_C) then no solution can exist.
Additionally, if x_R and x_C have different parities, no solution can exist; because x_R gives the global parity of ones needed to satisfy all the rows while x_C does the same for the columns (because we computed lower bounds while also accounting for parity.)
After all this, what about when everything holds, i.e. \max(x_R, x_C) \le \min(y_R, y_C) and parities match?
Well, in this case a solution always exists!
In fact there’s a rather ‘simple’ greedy algorithm to construct it as well.
First, let’s fix \max(x_R, x_C) to be the number of extra ones we’ll introduce.
Using this, we’ll then fix the number of ones in each row/column.
This can be done as follows:
- Suppose x_R \le x_C (if not, swap the rows/columns for this argument.)
- For each column, simply use CL_i ones. This will sum up to x_C.
- For each row, start out with RL_i ones.
Then, repeatedly increase the ones in some row by 2, as long as you don’t go over the upper bound - do this till the sum reaches x_C.- This is always possible because \max(x_R, x_C) \le \min(y_R, y_C), so we will not “run out” of possible increases.
Once all the row and column one-counts are known, the following algorithm works:
- Pick a row with the largest remaining one-count.
- Suppose it needs k ones.
- Pick the k remaining columns with the largest required one-counts, and place a 1 in each of these columns; at the specified rows.
This rather simple-looking greedy algorithm will solve the problem!
Why?
The idea here is to see the process of placing ones, as building a bipartite graph between the rows and columns.
In that regard, knowing the counts of ones in the rows/columns is the same as knowing the degrees of each vertex; and the objective is to then realize that as a graph.
The final greedy algorithm used was then nothing but the Havel-Hakimi algorithm which is why it was correct.There’s only one thing that really needs proper justification here: when padding degrees to make the row and column total degrees equal, we didn’t take any care as to which degrees were incremented; so a natural question is whether doing this differently could cause the resulting degree sequence to change whether it’s constructible or not.
This, luckily for us, has been studied before - because we’re dealing with a bipartite graph, the Gale-Ryser theorem applies, and it can be verified that our method of augmenting degrees till they match results in a pair of degree sequences that satisfy the condition for the theorem.
TIME COMPLEXITY:
\mathcal{O}(30\cdot(NM + N\log N + M\log M)) 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());
int main()
{
ios::sync_with_stdio(false); cin.tie(0);
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;
vector ans(n, vector(m, 0));
auto tmp = ans;
auto solve = [&] (auto rowinf, auto colinf) {
for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) tmp[i][j] = 2;
int xorchk = 0;
// fix rows
for (int i = 0; i < n; ++i) {
auto [x, o, a] = rowinf[i];
if (a == 1 and o == 0) return -1;
xorchk ^= x;
if (a == 1) for (int j = 0; j < m; ++j) tmp[i][j] = 1;
if (o == 0) for (int j = 0; j < m; ++j) tmp[i][j] = 0;
}
// fix cols
for (int i = 0; i < m; ++i) {
auto [x, o, a] = colinf[i];
if (a == 1 and o == 0) return -1;
xorchk ^= x;
if (a == 1) for (int j = 0; j < n; ++j) {
if (tmp[j][i] != 2 and tmp[j][i] != 1) return -1;
tmp[j][i] = 1;
}
if (o == 0) for (int j = 0; j < n; ++j) {
if (tmp[j][i] != 2 and tmp[j][i] != 0) return -1;
tmp[j][i] = 0;
}
}
if (xorchk) return -1;
// some rows are fixed, some cols are fixed
// no conflicts so far
// find min and max ones per row and per col
int rowmin = 0, rowmax = 0;
int colmin = 0, colmax = 0;
vector rowlo(n, 0), rowhi(n, 0);
vector collo(m, 0), colhi(m, 0);
for (int i = 0; i < n; ++i) {
array<int, 3> ct{};
for (int j = 0; j < 3; ++j) ct[j] = ranges::count(tmp[i], j);
if (ct[2] == 0) continue;
int lo = 0, hi = ct[2];
if (ct[1] == 0) ++lo;
if (ct[0] == 0) --hi;
int reqx = rowinf[i][0] ^ (ct[1] % 2);
if (lo%2 != reqx) ++lo;
if (hi%2 != reqx) --hi;
if (lo > hi) return -1;
rowlo[i] = lo, rowhi[i] = hi;
rowmin += lo;
rowmax += hi;
}
for (int i = 0; i < m; ++i) {
array<int, 3> ct{};
for (int j = 0; j < n; ++j) ct[tmp[j][i]] += 1;
if (ct[2] == 0) continue;
int lo = 0, hi = ct[2];
if (ct[1] == 0) ++lo;
if (ct[0] == 0) --hi;
int reqx = colinf[i][0] ^ (ct[1] % 2);
if (lo%2 != reqx) ++lo;
if (hi%2 != reqx) --hi;
if (lo > hi) return -1;
collo[i] = lo, colhi[i] = hi;
colmin += lo;
colmax += hi;
}
if (rowmin%2 != colmin%2) return -1;
if (max(rowmin, colmin) > min(rowmax, colmax)) return -1;
for (int i = 0; i < n; ++i) {
while (rowlo[i]+2 <= rowhi[i]) {
if (rowmin >= colmin) break;
rowlo[i] += 2;
rowmin += 2;
}
}
for (int i = 0; i < m; ++i) {
while (collo[i]+2 <= colhi[i]) {
if (colmin >= rowmin) break;
collo[i] += 2;
colmin += 2;
}
}
// set all undefined to 0
for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) tmp[i][j] %= 2;
// now fill greedily
priority_queue<array<int, 2>> pqrow;
for (int i = 0; i < n; ++i) {
if (rowlo[i] > 0) pqrow.push({rowlo[i], i});
}
priority_queue<array<int, 2>> pqcol;
for (int i = 0; i < m; ++i) {
if (collo[i] > 0) pqcol.push({collo[i], i});
}
while (!pqrow.empty()) {
auto [deg, r] = pqrow.top(); pqrow.pop();
vector<array<int, 2>> reins;
assert(deg <= (int)pqcol.size());
for (int i = 0; i < deg; ++i) {
auto [deg2, c] = pqcol.top(); pqcol.pop();
tmp[r][c] = 1;
if (deg2 > 1) reins.push_back({deg2-1, c});
}
for (auto x : reins) pqcol.push(x);
}
// final check
for (int i = 0; i < n; ++i) {
auto [x, o, a] = rowinf[i];
int cx = 0, co = tmp[i][0], ca = tmp[i][0];
for (int j = 0; j < m; ++j) {
cx ^= tmp[i][j];
co |= tmp[i][j];
ca &= tmp[i][j];
}
if (cx != x or co != o or ca != a) return -1;
}
for (int i = 0; i < m; ++i) {
auto [x, o, a] = colinf[i];
int cx = 0, co = tmp[0][i], ca = tmp[0][i];
for (int j = 0; j < n; ++j) {
cx ^= tmp[j][i];
co |= tmp[j][i];
ca &= tmp[j][i];
}
if (cx != x or co != o or ca != a) return -1;
}
return 0;
};
for (int b = 0; b < 30; ++b) {
auto curr = rows, curc = cols;
for (auto &x : curr) for (auto &y : x) y = (y & (1 << b)) >> b;
for (auto &x : curc) for (auto &y : x) y = (y & (1 << b)) >> b;
if (solve(curr, curc) == -1) {
ans[0][0] = -1;
break;
}
for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) {
ans[i][j] |= tmp[i][j] << b;
}
}
if (ans[0][0] == -1) cout << -1 << '\n';
else {
for (auto row : ans) {
for (int x : row) cout << x << ' ';
cout << '\n';
}
}
}
}