---
id: 668
lang: en
translation_of: index.md
source_sha256: 73434744c9fe79ce3ddac941331dadad4680ad68d756bb6bbd87d7d7512ea71d
title: "Combinatorics in OI"
description: "Combinatorics is an important topic tested in OI."
tags: ["OI","Math","Combinatorics","Permutations","Permutations and Combinations","Derangements","Catalan Numbers","Stirling Numbers"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "排列(permutation) — the parenthetical English gloss is dropped, since it would just repeat the translated word."
  - "弱化版 rendered literally as “weakened version” (standard OI usage for an easier variant of a problem), with no chip."
  - "Problem name 小朋友的球 (P1655) rendered as “The Kids' Balls”."
  - "Book title 《组合数学》 rendered as “Combinatorics” in curly quotes."
  - "映射计数 rendered as “counting by bijection”."
  - "The author writes both Prüfer and Prufer; each spelling is kept where it appears."
  - "In the last paragraph, 序列种 read as 序列中 (“in the sequence”)."
---

## Contents

- Overview and Basic Concepts
- Permutations
- Combinations
- Stars and Bars
- Stirling Numbers
  - First Kind
  - Second Kind
- Derangements
- Catalan Numbers
- Permutations and Combinations of Multisets
- Prüfer Sequences
- Tricks for Permutations and Combinations in OI
- References

<!--more-->

## Overview and Basic Concepts

Combinatorics is an important exam topic in OI. Before we start explaining combinatorics, let's first establish a few concepts:

**Factorial**: the factorial of a positive integer is the product of the consecutive integers from 1 up to that number, written $n!$. The factorial of a number can be written as:
$$
n! = 1\times 2\times 3\times \dots \times n, n \in N^*
$$

## Permutations

A permutation is an operation that was born to solve the following problem:

> Take k elements out of n elements; find the number of arrangements of the k elements.

So we can write this problem as $P_n^k$. Let's derive the general solution to this problem. First, pin down the range: clearly $k \leq n$. Next, we notice that the number of choices each time we take an element depends on the order in which the elements are taken. When we pick an element for the $k$-th time, we find that we have $n-k+1$ choices; when we pick an element for the $k-1$-th time, we have $n-k+2$ choices... and so on. By the multiplication principle we get the following formula:

$$
P_n^k = n \times (n-1) \times (n-2) \times \dots \times (n-k+1)
$$

Using the factorial we introduced above, we can simplify it to:

$$
P_n^k = \frac{n!}{(n-k)!}
$$

## Combinations

Combinations are really a “weakened version” of permutations. Combinations focus on solving this kind of problem:

> Take a set of k elements out of n elements; how many ways are there to choose the set?

Then this is very obvious: we just need to cancel out the duplicate arrangements in the permutation problem. The exact answer is:

$$
{n \choose k} = \frac{P_n^k}{k!} = \frac{n!}{(n-k)!k!}
$$

## Stars and Bars

Stars and bars actually comes up a lot in <span class="slang" data-zh="高考" data-gloss="gāokǎo, “higher exam”. China's national college entrance exam, taken at the end of high school.">college entrance exam</span> math. Here I'll briefly go over a few classic problems and then wrap up my account of stars and bars.

**Example** Divide a row of $n$ people into $d$ groups. How many ways are there?\
**Solution** We notice that among the $n$ people there are $n-1$ gaps, so the problem can be turned into the number of ways to pick, out of the $n-1$ gaps, $d$ of them, and the answer is clearly $n-1 \choose d$.

## Stirling Numbers

### First Kind

Haven't learned it yet, <span class="slang" data-zh="弃坑" data-gloss="qì kēng, “abandoning the pit”. A 坑 is a project or topic one has started; giving up on it and leaving it unfinished.">dropping this one</span>.

### Second Kind

Example problem: [P1655: The Kids' Balls](https://www.luogu.org/problemnew/show/P1655)

The problem that Stirling numbers mainly solve is this:

> The Stirling number of the second kind is the number of ways to define k **equivalence** classes on n elements. —[Wikipedia](https://zh.wikipedia.org/wiki/%E6%96%AF%E7%89%B9%E7%81%B5%E6%95%B0)

Its recurrence is:

$$
S(n, k) = S(n-1,k-1)+kS(n-1,k)
$$

Detailed explanation: an account of the recurrence: consider the n-th item. Item n can form a non-empty set on its own, in which case the first n-1 items form k-1 non-empty indistinguishable sets, giving $S(n-1,k-1)$ ways; or the first n-1 items can form k non-empty indistinguishable sets, with the n-th item put into any one of them, giving $k*S(n-1,k)$ ways. (src:Wikipedia)

Code for the example problem:

```python
# P1655.py
MAX_N = 405
stiring = [[0]*MAX_N for i in range(MAX_N)]
for i in range(1, MAX_N):
    stiring[i][i] = stiring[i][1] = 1
    for j in range(2, i):
        stiring[i][j] = stiring[i - 1][j - 1] + j * stiring[i - 1][j]
while True:
    try:
        n, m = map(int, input().split())
        print(stiring[n][m])
    except EOFError:
        break
```

## Derangements

The derangement problem refers to this kind of problem:

> Let the length of a permutation be $n$. How many arrangements are there in which no number is in its own position?

This problem is rather interesting. Its recurrence:

$$
D_n = nD_{n-1}+(-1)^n
$$

This sequence can solve a lot of problems. The author can't recall offhand which problem on Luogu it was, and will add it here once it comes back.

## Catalan Numbers

The recurrence for the Catalan numbers is:

$$
Cat_n = \frac{2n \choose n}{n+1}
$$

The meaning of the Catalan numbers is:

> Given a sequence of length $n$, at position $i$, let the prefix count of $0$s be $zero[i]$ and the prefix count of $1$s be $one[i]$. For every $i \leq n$, we have $zero[i] \geq one[i]$.

The following problems are all related to the Catalan numbers:

- The number of valid bracket sequences
- The number of full binary trees with $n$ nodes
- The number of paths in the Cartesian plane from $(0,0)$ to $(n,n)$ that do not pass through the line $y=x$ is $2Cat_{n-1}$.
- The number of stack push/pop sequences of $n$ elements
- $Cat_n$ is the number of ways to divide a convex polygon with $n+2$ sides into triangles by connecting vertices.
- $Cat_n$ is the number of ways to fill a staircase shape of height $n$ with $n$ rectangles.

### Proof of the Catalan Numbers

Here we prove why the Catalan numbers can represent the number of valid bracket sequences. (The idea of the proof below comes from Chapter 8, Section 1 of “Combinatorics”.)

**Lemma**

The number of valid bracket sequences of length $2n$ is $Cat_n$.

**Proof**

We turn a bracket sequence of length $2n$ into a sequence made up of $1, -1$, and we call it a **valid sequence** if and only if $\forall x \in [1, 2n], \sum_{i = 1}^x \geq 0$; in other words, every prefix sum of a valid sequence is greater than $0$. A sequence that does not satisfy the condition above we call an **invalid sequence**. Clearly, the number of sequences of length $2n$ is the sum of the numbers of valid and invalid sequences. We define the number of valid sequences of length $2n$ as $A_n$, and the number of invalid sequences of length $2n$ as $U_n$. From the discussion above, we have:

$$
A_n + U_n = {2n \choose n}
$$

Our goal is to compute $A_n$, and we can consider getting it by finding $U_n$. Consider an invalid sequence of length $2n$, $a_1, a_2, \dots, a_{2n}$. There must exist a smallest $k$ such that:

$$
\sum_{i = 1}^k a_i < 0
$$

Since $a_k$ can take only two values and $k$ is the smallest, $a_k = -1$ and $\sum_{i = 1}^{k - 1} a_i = 0$. We also notice that $k$ should be odd (the reader is invited to think about why). Now, we negate each of the first $k$ terms of this sequence and leave the rest unchanged, swapping, among the first $k$ terms, $-1$ and $1$; the transformed sequence is then a sequence made up of $n+1$ copies of $+1$ and $n-1$ copies of $-1$. We can consider counting by bijection (readers who want to learn about counting by bijection can refer to [this article](https://zepto.page/post/bijection-in-use)), that is: there exists a first sequence made up of $n+1$ copies of $+1$ and $n-1$ copies of $-1$, i.e. there exists a first sequence in which the count of $+1$ exceeds the count of $-1$; after negating all the signs, this means there exists a first sequence in which the count of $-1$ exceeds the count of $+1$, which is an invalid sequence. These two kinds of sequences are in **one-to-one correspondence**. So the value of $U_n$ equals the number of first sequences in which the count of $+1$ exceeds the count of $-1$:

$$
\frac{(2n)!}{(n+1)!(n-1)!}
$$

Then, after substituting into the original equation and subtracting, we get the final result for the Catalan numbers.

This completes the proof.

## Permutations and Combinations of Multisets

### Definition of a Multiset

A multiset is a set in which the number of elements of each kind may be more than one. We usually denote it with the following notation:

$$
S_m=\{ n_1*a_1, n_2*a_2, n_3*a_3, \dots, n_k*a_k \}
$$

where $a_i$ is the kind of element and $n_i$ is the number of elements of kind $i$.

### Combinations of Multisets

Let's first consider a weakened version of the multiset combination problem:

Given a multiset $S_m=\{ n_1*a_1, n_2*a_2, n_3*a_3, \dots, n_k*a_k \}$, how many ways are there to take $r$ elements? ($\forall i \in [1,k\, r\leq n_i]$).

This problem is easy to solve: we just turn it into the problem of being given $k-1$ separator elements $b$ and $r$ elements to choose from, and find the number of their full permutations:

$$
k+r-1 \choose r
$$

So if we remove $\forall i \in [1,k\, r\leq n_]$, how do we compute it?

We can consider the inclusion–exclusion principle. Here $k+r-1 \choose r$ means the number of choices ignoring the element limits. In the inclusion–exclusion, first we subtract the cases with $n_1+1$ copies of $a_1$, that is, $k+r-1-a_1-1 \choose r$. Then we subtract the number of cases with $n_2+1$ copies of $a_2$, and we find that one part has been subtracted twice: the intersection of these two cases, so we need to add it back: $+{k+r-1-a_1-1-a_2-1 \choose r}$. By the inclusion–exclusion theorem, the final result is:

$$
{k+r-1 \choose r} - \sum_{i=1}^{k} {k+r-n_i-2 \choose r} + \sum_{i<j}^{k} {k+r-n_i-n_j-3 \choose r} - \dots
$$

## Prüfer Sequences and Unrooted Trees

Normally, an unrooted tree is mostly represented as a picture or as a set of edge triples. Now let me introduce a kind of sequence that can correspond to the shape of an unrooted tree, so that we can study it from the angle of permutations and combinations. First, the Prüfer sequence corresponding to the tree in the figure below is: $4,4,4,5$.

![Unrooted tree](media/124px-Tree_graph.svg_.png "Public domain, https://commons.wikimedia.org/w/index.php?curid=592812")

Let me describe how to turn an unrooted tree into a Prufer sequence:

1. Find the leaf with the smallest label, delete it, and add the only node adjacent to it to the Prufer sequence.
2. Repeat the first step until only two nodes remain in the tree.

We can see that the number of times a node appears in the Prufer sequence is the node's degree minus one, and the length of this sequence is $n-2$. So, because of these two properties, some formulas arise.

**Lemma 1**   The number of unrooted trees with $n$ nodes and different shapes is $n^{n-2}$.

This is easy to understand: map Prufer sequences of length $n-2$ onto unrooted trees, and it follows by permutations and combinations.

**Lemma 2**   If the number of nodes $n$ and the degree $d_i$ of every node are given, then there are $\frac{(n-2)!}{\prod_{i = 1}^n (d_i-1)!}$ trees of different shapes.

This is really just permutations of a multiset. In a Prufer sequence of length $n-2$, there are $d_i-1$ occurrences of the $i$-th node; I won't belabor it further.

## References

sources:

[https://oi-wiki.org/math/stirling/](https://oi-wiki.org/math/stirling/)\
[https://zh.wikipedia.org/wiki/%E9%94%99%E6%8E%92%E9%97%AE%E9%A2%98](https://zh.wikipedia.org/wiki/%E9%94%99%E6%8E%92%E9%97%AE%E9%A2%98)\
[https://zh.wikipedia.org/wiki/%E5%8D%A1%E5%A1%94%E5%85%B0%E6%95%B0](https://zh.wikipedia.org/wiki/%E5%8D%A1%E5%A1%94%E5%85%B0%E6%95%B0)
