The standard shape of a “-1 or construct” problem: an invariant gives a necessary condition, and a construction shows the condition is also sufficient. Find the invariant by asking what one operation preserves; find the construction by making the problem smaller (fix one position for good per operation).
| Operation | Invariant | Construction idea |
|---|---|---|
| set to | total xor when is even | sweep forward with , then backward |
| add to two adjacent elements | alternating sum | fix positions left to right |
| swap two elements, cost by distance | multiset | cycle decomposition |
| flip a row or a column of a binary matrix | decide the first row and column, the rest is forced | |
| choose , , | weighted sums | process from the left, forced counts |
Equalize by triple xor
Operation: pick distinct and set all three to . Make all elements equal in at most operations, or report impossible.
vector<array<int, 3>> equalizeByXor(vector<int> a) { // op (i,j,k): all three := a_i ^ a_j ^ a_k; at most n ops; {{-1,-1,-1}} if impossible
int n = sz(a); vector<array<int, 3>> ops;
if (n % 2 == 0) {
int x = 0; for (int v : a) x ^= v;
if (x) return {{-1, -1, -1}};
n--; // solve the first n-1; the last equals their common value (xor 0)
}
for (int i = 0; i + 2 < n; i += 2) ops.push_back({i, i + 1, i + 2});
for (int i = n - 5; i >= 0; i -= 2) ops.push_back({i, i + 1, i + 2});
return ops;
}Proof: possible iff n is odd or the total xor is 0
Invariant. After the operation the three positions hold each, whose xor is , the same as before; so the total xor never changes. If is even and all elements end equal to , the total xor is . Construction for odd . The forward pass makes the last position and every even position from the second operation onward carry the running xor; after it, positions equal the total xor , and every pair for even is equal. The backward pass sets each triple to , where is the common value of the pair. So all elements become , using operations. Even with total xor : solve the first elements (odd count); they all become their xor, which equals because the total xor is . Tested on random arrays with , including the operation count.
Related: Parity and Coloring, Invariants.