Three problems rated 1,700 to 1,800 that count sets, orders and loads under a prime modulus. The move: build the factorial tables once, then every count is a few reads and products.
This tent holds three problems rated 1,700 to 1,800. Each asks how many sets, orders or loads fit a rule, for up to 10^5 queries with values up to 10^6. The answer is reported modulo the prime 1,000,000,007, because it has thousands of digits.
The first solution lists the objects, or builds a table of all smaller counts. It is correct on tiny inputs and cannot work at the limits.
| Problem | The literal route | Its size at the limits |
|---|---|---|
| Ways to choose the weekend winners | multiply k terms for each draw | 10^11 products |
| Sponsor clips with a protected opener | list every order of the clips | 20! = 2,432,902,008,176,640,000 orders for a break of 20 |
| Parcels, vans and a loading cap | a table over vans and parcels | 9 × 10^10 cells |
The count itself is a formula. The work is evaluating that formula 10^5 times, quickly.
Exercise · Predict the output: Parcels with a cap. 5 identical parcels go into 3 different vans, and a van holds at most 2. This counts the plans by inclusion and exclusion over the vans that break the cap. What does it print?
c = [[0] * 9 for _ in range(9)]
for n in range(9):
c[n][0] = 1
for k in range(1, n + 1):
c[n][k] = c[n - 1][k - 1] + c[n - 1][k]
total = 0
for j in range(4):
left = 5 - j * 3
if left < 0:
break
term = c[3][j] * c[left + 2][2]
total += -term if j % 2 == 1 else term
print(total)Every count in this tent is a product of binomial coefficients and factorials. A binomial coefficient is n! divided by k! and (n - k)!, and division under a prime modulus is a multiplication by an inverse. So build two tables once, up to the largest n.
Build fact[i] and inv_fact[i] for i up to the largest value, once. Then n choose k is fact[n] × inv_fact[k] × inv_fact[n - k], with every product reduced.
Computing an inverse with a fast power for each i costs about 60 steps each, so fill inv_fact in one pass. Take one inverse, for the top factorial, with a fast power. Then walk down: inv_fact[i - 1] = inv_fact[i] × i. That is one fast power and n products for the whole table.
The other two problems turn a rule into a choice of places. For the clips, put the other clips down first, then pick the gaps after them for the sponsors. For the vans, count the plans with no cap, then correct for the vans that break it.
Fill the inverse factorials from the top down: one fast power for the last, then each earlier one is the next times its index.
Exercise · Find the bug: One gap too many. A break plays a row of different clips. Some are sponsor clips. The first clip is never a sponsor, and no two sponsors are neighbours. This counts the orders. Which line is wrong?
def break_orders(clips, sponsors):
free = clips - sponsors
if sponsors > free:
return 0
ways = 1
for i in range(1, free + 1):
ways *= i
gaps = free + 1
for i in range(gaps - sponsors + 1, gaps + 1):
ways *= i
return waysThe Academy lessons Bits and maths, Subsets and permutations and DP from recursion counted objects by generating them. This tent counts without generating any. Choose the places, then count the orders, then multiply.
That habit solves the clip problem. With f other clips, the sponsors sit in m of the f gaps behind them. They can be ordered in f!/(f - m)! ways, and the other clips come in f! orders. For 3 clips with 1 sponsor the count is 2 × 2 = 4, and a brute force over all 6 orders agrees.
The cap on the vans uses inclusion and exclusion. Plans with no cap are the stars and bars count. Subtract the plans where j chosen vans each hold at least cap + 1, with the sign plus for even j and minus for odd j.
The trap is in the modulus. A reduced factorial is not a multiple of the smaller ones, so integer division of reduced factorials gives nonsense.
Reduced factorials are no longer multiples of one another, so integer division is wrong from thirteen factorial; multiply by an inverse.
Exercise · Break it: The division that is not exact. This returns n choose k modulo 1,000,000,007. It stores every factorial modulo the prime and divides with integer division. Find an input where it is wrong.
def choose_mod(n, k):
MOD = 1_000_000_007
if k > n:
return 0
fact = [1] * (n + 1)
for i in range(1, n + 1):
fact[i] = fact[i - 1] * i % MOD
return fact[n] // (fact[k] * fact[n - k]) % MOD| Limit | What it tells you |
|---|---|
| n up to 10^6, 10^5 queries | tables of 10^6 + 1 entries, built once |
| parcels + vans up to 6 × 10^5 | the tables must reach parcels + vans, not parcels alone |
| answers modulo 1,000,000,007 | a product of two residues reaches 10^18: 64-bit integers |
| a signed sum in inclusion and exclusion | take the remainder at the end: % can be negative in Java and C++ |
| k above n | the count is 0: check it before you index the tables |
The full treatment is in Fast I/O and stress testing. In JavaScript a product of two residues is beyond 2^53, so the code below multiplies with BigInt.
import sys
def main():
MOD = 1_000_000_007
data = sys.stdin.buffer.read().split()
q = int(data[0])
ns = [int(data[1 + 2 * i]) for i in range(q)]
ks = [int(data[2 + 2 * i]) for i in range(q)]
top = max(ns)
fact = [1] * (top + 1)
for i in range(1, top + 1):
fact[i] = fact[i - 1] * i % MOD
inv_fact = [1] * (top + 1)
inv_fact[top] = pow(fact[top], MOD - 2, MOD)
for i in range(top, 0, -1):
inv_fact[i - 1] = inv_fact[i] * i % MOD
out = []
for n, k in zip(ns, ks):
out.append(0 if k > n else fact[n] * inv_fact[k] % MOD * inv_fact[n - k] % MOD)
sys.stdout.write("\n".join(map(str, out)) + "\n")
main()import java.io.*;
import java.util.*;
public class Main {
static final long MOD = 1_000_000_007L;
static long power(long base, long exp) {
long result = 1;
base %= MOD;
while (exp > 0) {
if ((exp & 1) == 1) result = result * base % MOD;
base = base * base % MOD;
exp >>= 1;
}
return result;
}
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int q = (int) in.nval;
int[] ns = new int[q], ks = new int[q];
int top = 0;
for (int i = 0; i < q; i++) {
in.nextToken();
ns[i] = (int) in.nval;
in.nextToken();
ks[i] = (int) in.nval;
top = Math.max(top, ns[i]);
}
long[] fact = new long[top + 1], invFact = new long[top + 1];
fact[0] = 1;
for (int i = 1; i <= top; i++) fact[i] = fact[i - 1] * i % MOD;
invFact[top] = power(fact[top], MOD - 2);
for (int i = top; i >= 1; i--) invFact[i - 1] = invFact[i] * i % MOD;
StringBuilder out = new StringBuilder();
for (int i = 0; i < q; i++) {
long ways = ks[i] > ns[i] ? 0 : fact[ns[i]] * invFact[ks[i]] % MOD * invFact[ns[i] - ks[i]] % MOD;
out.append(ways).append("\n");
}
System.out.print(out);
}
}#include <iostream>
#include <vector>
using namespace std;
const long long MOD = 1000000007LL;
long long power(long long base, long long exp) {
long long result = 1;
base %= MOD;
while (exp > 0) {
if (exp & 1) result = result * base % MOD;
base = base * base % MOD;
exp >>= 1;
}
return result;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int q;
cin >> q;
vector<int> ns(q), ks(q);
int top = 0;
for (int i = 0; i < q; i++) {
cin >> ns[i] >> ks[i];
top = max(top, ns[i]);
}
vector<long long> fact(top + 1, 1), invFact(top + 1, 1);
for (int i = 1; i <= top; i++) fact[i] = fact[i - 1] * i % MOD;
invFact[top] = power(fact[top], MOD - 2);
for (int i = top; i >= 1; i--) invFact[i - 1] = invFact[i] * i % MOD;
for (int i = 0; i < q; i++) {
long long ways = ks[i] > ns[i] ? 0 : fact[ns[i]] * invFact[ks[i]] % MOD * invFact[ns[i] - ks[i]] % MOD;
cout << ways << "\n";
}
}const data = require("fs").readFileSync(0, "utf8").split(/\s+/).filter(Boolean).map(Number);
const MOD = 1000000007;
const MODN = 1000000007n;
const mul = (a, b) => Number(BigInt(a) * BigInt(b) % MODN);
function power(base, exp) {
let result = 1;
while (exp > 0) {
if (exp % 2 === 1) result = mul(result, base);
base = mul(base, base);
exp = Math.floor(exp / 2);
}
return result;
}
const q = data[0];
const ns = [], ks = [];
let top = 0;
for (let i = 0; i < q; i++) {
ns.push(data[1 + 2 * i]);
ks.push(data[2 + 2 * i]);
top = Math.max(top, ns[i]);
}
const fact = new Array(top + 1).fill(1);
for (let i = 1; i <= top; i++) fact[i] = mul(fact[i - 1], i);
const invFact = new Array(top + 1).fill(1);
invFact[top] = power(fact[top], MOD - 2);
for (let i = top; i >= 1; i--) invFact[i - 1] = mul(invFact[i], i);
const out = [];
for (let i = 0; i < q; i++) {
out.push(ks[i] > ns[i] ? 0 : mul(mul(fact[ns[i]], invFact[ks[i]]), invFact[ns[i] - ks[i]]));
}
process.stdout.write(out.join("\n") + "\n");On the sample 3 and the draws 5 2, 10 3 and 7 9, all four programs print 10, 120 and 0, one per line.
The slow twin takes the exact binomial coefficient from Python's integers, then reduces it. It does not use inverses, so it cannot share a mistake with the fast code.
import random
from math import comb
from fast import choose_mod
for seed in range(1000):
rng = random.Random(seed)
n = rng.randint(0, 30)
k = rng.randint(0, n + 2)
if choose_mod(n, k) != comb(n, k) % 1_000_000_007:
print("different at", n, k)
break
else:
print("all 1000 inputs agree")The run prints all 1000 inputs agree. Replace the inverses by integer division of the reduced factorials, and the first random input fails: for n = 27 and k = 12 it gives 0 instead of 17,383,860.
At 1,600 to 1,800 the formula is standard, and the work is seeing which places to choose and which order to count. Write the formula in one line before you code, and check it by hand against a brute force on at most 6 items. Aim for about 30 minutes a problem, with 10 for the stress test.
The first problem is the tables themselves. The second turns a rule about neighbours into a choice of gaps. The last, rated 1,800, adds a cap to each box and corrects for it by inclusion and exclusion.
For each problem, write the formula in one line and check it by hand on 4 or 5 items. Then compare the fast code with a brute force on tiny inputs.
Checkpoint · Combinatorics and modular counting
Q1/5 You must answer n choose k modulo a prime for 10^5 draws with n up to 10^6. What do you build?
Answer: B
Pascal's triangle has about 5 × 10^11 cells. The two tables have 10^6 entries each, and each draw is three reads and two products.
Q2/5 A break has 4 different clips, one of them a sponsor clip that may not open the break. How many orders are there?
Answer: C
The 3 other clips come in 3! = 6 orders, and the sponsor sits in one of 3 gaps behind them: 6 × 3 = 18. A brute force over all 24 orders agrees.
Q3/5 5 identical parcels go into 3 vans, with at most 2 in a van. How many plans are there?
Answer: C
There are 21 plans with no cap. Subtract the 18 plans where a van holds at least 3, and none have two such vans: 21 - 18 = 3.
Q4/5 Why is fact[13] // (fact[1] × fact[12]) wrong when the factorials are stored modulo 1,000,000,007?
Answer: B
13! = 6,227,020,800 is above the modulus, so the stored value is 227,020,758. Divided by 479,001,600 it gives 0. Multiply by an inverse instead.
Q5/5 Why do the products in these solutions need 64-bit integers?
Answer: B
A 32-bit signed integer stops at 2,147,483,647. A product of two residues can reach about 10^18, so use 64-bit products and reduce after each one.
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.