Three counting problems rated 1,500 to 1,600 with far too many objects to list. The move: count by structure, with a basis, a formula or a table over the set of used items, modulo a prime.
This tent holds three problems rated 1,500 to 1,600, and each one counts objects that no program can list. A set of 100,000 services has 2^100000 subsets. An arrangement of 100,000 products has 100,000 factorial orders. Even 13 ledgers have 6,227,020,800 orders.
| Problem | What is counted | The structure | The size of the work |
|---|---|---|---|
| Restart sets that match the alarm pattern | subsets with a given xor | a linear basis of the masks | 20 reductions per mask |
| Re-slotting shelves with some bins unchanged | arrangements with exactly s fixed bins | a binomial times a recurrence | one pass up to n |
| Audit orders with no conflicting neighbours | permutations with a rule on neighbours | a table over the used set and the last item | 2^13 × 13 states |
The xor problem needs a basis, so look at it first. A basis is a short list of masks with different top bits, from which any xor of the masks can be built.
To add a mask, reduce it from the top bit down: whenever its top bit already has a basis mask, xor with that mask. If the mask becomes 0, it is a combination of earlier masks. Otherwise it joins the basis at its top bit.
Exercise · Predict the output: Does the third mask join the basis?. The masks are 3, 5 and 6, and every mask is below 8. This adds each mask to a basis, from the top bit down, and prints the rank and 2 to the power of the masks left over. What does it print?
masks = [3, 5, 6]
basis = [0] * 3
rank = 0
for mask in masks:
for bit in range(2, -1, -1):
if ((mask >> bit) & 1) == 0:
continue
if basis[bit] == 0:
basis[bit] = mask
rank += 1
break
mask ^= basis[bit]
print(rank, 1 << (len(masks) - rank))Before any code, ask what structure the objects have. If the objects are subsets and the question is about an xor, the structure is a basis. If they are arrangements with a rule on a few items, the structure is a choice of those items and a recurrence for the rest. If the set of items is small, the structure is the set itself, as a bit mask.
Split the objects into independent choices, or index a table by the set of used items, and take every count modulo the prime.
For the xor problem the structure gives a clean count. Reduce the target by the basis. If it does not reach 0, no subset builds it, and the count is 0.
If it does, exactly 2^(n - rank) subsets build it. The 2^n subsets reach only 2^rank different patterns, and every reachable pattern is reached equally often. For the masks 3, 5 and 6 and the target 5, the count is 2.
Reduce the target by the basis; if it reaches zero, exactly 2 to the n minus rank subsets build it.
The arrangements split in two. Choose which s of the n products stay, in C(n, s) ways, and rearrange the other m = n - s so that none stays. Let d(m) be the number of such rearrangements.
It follows d(m) = (m - 1) × (d(m - 1) + d(m - 2)), with d(0) = 1 and d(1) = 0. For n = 5 and s = 2 the count is 10 × d(3) = 10 × 2 = 20.
Exercise · Put it in order: No product stays. Arrange the lines into a function that returns d(m), the number of ways to rearrange m products so that no product stays in its bin.
def derangements(m):
d = [0] * (m + 2)
d[0] = 1
for i in range(2, m + 1):
d[i] = (i - 1) * (d[i - 1] + d[i - 2])
return d[m]
d[i] = i * (d[i - 1] + d[i - 2])The last problem has too many orders to count one by one, but the orders share their starts. The state is the set of ledgers used so far and the last one. From a state, add any unused ledger that does not conflict with the last one. For 13 ledgers there are 2^13 × 13 = 106,496 states, against 6,227,020,800 orders.
Exercise · Find the bug: The orders that must end at one ledger. This counts the orders of n ledgers in which no two neighbours conflict. The table holds the orders of a used set that end with a given ledger. Which line is wrong?
def count_audit_orders(n, conflicts):
clash = [0] * n
for a, b in conflicts:
clash[a] |= 1 << b
clash[b] |= 1 << a
ways = [[0] * n for _ in range(1 << n)]
for v in range(n):
ways[1 << v][v] = 1
for mask in range(1 << n):
for last in range(n):
if ways[mask][last] == 0:
continue
for nxt in range(n):
if ((mask >> nxt) & 1) or ((clash[last] >> nxt) & 1):
continue
ways[mask | (1 << nxt)][nxt] += ways[mask][last]
return ways[(1 << n) - 1][n - 1]The Academy lessons Bits and maths, Subsets and permutations and DP from recursion taught how to build every object and how to count with a table. Here the objects are too many to build, so you count them by structure.
Three things change. The counts exceed any integer type, so the statement asks for them modulo a prime, and a division becomes a multiplication by a modular inverse. The structure must be found before the table, because the right table is often a basis or a formula. And a small n is a hint: a limit of 13 means a state of 2^n times n.
The structure is easy to lose by half. For the re-slotting, count only the rearrangements of the products that move, and the choice of the staying products is forgotten. For 4 products and exactly 1 staying, there are 8 re-slottings, but d(3) alone gives 2.
Re-slotting needs the choice of which products stay, C(n, s), times the rearrangement of the rest.
Exercise · Break it: The products that stay. A re-slotting puts n products into n bins. Exactly stay products end in their own bin and none of the others does. This counts the rearrangements of the products that move, and nothing else. Find an input where it is wrong.
def count_reslots(n, stay):
if stay > n:
return 0
moved = n - stay
d = [0] * (moved + 2)
d[0] = 1
for i in range(2, moved + 1):
d[i] = (i - 1) * (d[i - 1] + d[i - 2])
return d[moved]| Limit | What it tells you |
|---|---|
| 10^5 masks below 2^20 | a basis of at most 20 entries, and about 2 × 10^6 reduction steps |
| n up to 10^5 and a prime modulus | factorials up to n, and one modular inverse for each division |
| 13 ledgers | 106,496 states and 1,384,448 transitions, not 6,227,020,800 orders |
The full treatment is in Fast I/O and stress testing. Here the first line holds the count and the target, and the second line the masks. The power of 2 is taken modulo the prime in 64 bits.
import sys
MOD = 1_000_000_007
def main():
data = sys.stdin.buffer.read().split()
n, target = int(data[0]), int(data[1])
basis = [0] * 20
rank = 0
for mask in map(int, data[2:2 + n]):
for bit in range(19, -1, -1):
if ((mask >> bit) & 1) == 0:
continue
if basis[bit] == 0:
basis[bit] = mask
rank += 1
break
mask ^= basis[bit]
for bit in range(19, -1, -1):
if ((target >> bit) & 1) == 1 and basis[bit] != 0:
target ^= basis[bit]
answer = pow(2, n - rank, MOD) if target == 0 else 0
sys.stdout.write(str(answer) + "\n")
main()import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
in.nextToken();
int target = (int) in.nval;
int[] basis = new int[20];
int rank = 0;
for (int i = 0; i < n; i++) {
in.nextToken();
int mask = (int) in.nval;
for (int bit = 19; bit >= 0; bit--) {
if (((mask >> bit) & 1) == 0) continue;
if (basis[bit] == 0) { basis[bit] = mask; rank++; break; }
mask ^= basis[bit];
}
}
for (int bit = 19; bit >= 0; bit--) {
if (((target >> bit) & 1) == 1 && basis[bit] != 0) target ^= basis[bit];
}
long mod = 1_000_000_007L, answer = 1;
for (int i = 0; i < n - rank; i++) answer = answer * 2 % mod;
System.out.println(target == 0 ? answer : 0);
}
}#include <iostream>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, target;
cin >> n >> target;
int basis[20] = {0};
int rank = 0;
for (int i = 0; i < n; i++) {
int mask;
cin >> mask;
for (int bit = 19; bit >= 0; bit--) {
if (((mask >> bit) & 1) == 0) continue;
if (basis[bit] == 0) { basis[bit] = mask; rank++; break; }
mask ^= basis[bit];
}
}
for (int bit = 19; bit >= 0; bit--) {
if (((target >> bit) & 1) == 1 && basis[bit] != 0) target ^= basis[bit];
}
const long long mod = 1000000007LL;
long long answer = 1;
for (int i = 0; i < n - rank; i++) answer = answer * 2 % mod;
cout << (target == 0 ? answer : 0) << "\n";
}const data = require("fs").readFileSync(0, "utf8").split(/\s+/).filter(Boolean).map(Number);
const n = data[0];
let target = data[1];
const basis = new Array(20).fill(0);
let rank = 0;
for (let i = 0; i < n; i++) {
let mask = data[2 + i];
for (let bit = 19; bit >= 0; bit--) {
if (((mask >> bit) & 1) === 0) continue;
if (basis[bit] === 0) { basis[bit] = mask; rank++; break; }
mask ^= basis[bit];
}
}
for (let bit = 19; bit >= 0; bit--) {
if (((target >> bit) & 1) === 1 && basis[bit] !== 0) target ^= basis[bit];
}
let answer = 1;
for (let i = 0; i < n - rank; i++) answer = (answer * 2) % 1000000007;
process.stdout.write((target === 0 ? answer : 0) + "\n");On the sample of 3 masks, 3, 5 and 6, with the target 5, all four programs print 2.
The slow twin tries every subset of the masks. It is slow, and you can check it by reading it. The generator draws short lists of small masks, so that targets are often reachable and often not.
import random
from fast import count_restart_sets
from slow import count_restart_sets as slow_count
for seed in range(1000):
rng = random.Random(seed)
flips = [rng.randint(0, 15) for _ in range(rng.randint(1, 10))]
target = rng.randint(0, 15)
if count_restart_sets(flips, target) != slow_count(flips, target):
print("different at", flips, target)
break
else:
print("all 1000 inputs agree")The run prints all 1000 inputs agree. Return 1 whenever the target can be built, and the first seed fails. The masks 13, 1, 8, 15, 12, 9 and 15 with the target 11 give 1 instead of 8.
At this band the structure is the work. Write what is counted and the structure in one line, and the size of the table in another, before you code. Aim for about 25 minutes a problem.
The first counts subsets with a basis. The second splits arrangements into a binomial and a recurrence. The last is a table over the used set, for a small number of ledgers.
For each problem, write what is counted, its structure, and the size of the work, in two lines, before you code. Then write the slow twin, which lists every object on tiny inputs, and stress test.
Checkpoint · Counting and bit states
Q1/5 The masks are 3, 5 and 6, and the target is 5. How many subsets have the xor 5?
Answer: B
The rank is 2, because 6 is the xor of 3 and 5. A reachable target is built by 2^(3 - 2) = 2 subsets: the single mask 5, and the masks 3 and 6.
Q2/5 How many ways can 5 products be re-slotted so that exactly 2 stay in their own bin?
Answer: C
Choose the 2 staying products in C(5, 2) = 10 ways. The other 3 can be rearranged with no fixed product in d(3) = 2 ways. So 10 × 2 = 20.
Q3/5 How many states does the bitmask table have for 13 ledgers, counting the used set and the last ledger?
Answer: B
There are 2^13 = 8,192 used sets and 13 choices of the last ledger, which is 106,496. The 6,227,020,800 is the number of orders, which the table avoids listing.
Q4/5 For 3 ledgers and no conflicts, a count reads only the cell of the order that ends with the last ledger. What does it return?
Answer: B
Only the orders that end with ledger 2 are counted: 2 of the 6 orders. A complete order may end with any ledger, so the answer is the sum over every last ledger.
Q5/5 How many ways can 4 products be rearranged so that none stays in its bin?
Answer: B
The recurrence gives d(4) = 3 × (d(3) + d(2)) = 3 × (2 + 1) = 9. All 24 rearrangements would count the ones that keep a product in place.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.