← All problems

Hunting the Beast

Codeforces · Round #1105 (Div. 1) · Problem D

Problem

A graph is called functional if every node has exactly one outgoing edge, and no edge points from a node to itself (no self-loops).

Given a functional graph on nn nodes, we can choose a set of mm special nodes. A selection is good if every node in the graph is either special, or reachable from a special node in 1 or more steps.

Given nn and mm (1mn106)(1 \leq m \leq n \leq 10^6), count the number of good selections, summed over all possible functional graphs on nn nodes, modulo 998244353998244353.

Initial Observations
  1. [From experience] the graph is a collection of cycles with trees attached to them.
  2. Combinatorics + DP + recursion?
  3. nn choose mm — does it matter which mm you choose? (By symmetry, probably not.)
  4. 1mn1061 \leq m \leq n \leq 10^6, so we need O(n)O(n) or O(nlogn)O(n \log n).
  5. This seems hard.
  6. All leaves have to be special.
  7. [Exploit symmetry / constraints] A lot of symmetry here — does some formula simplify?
  8. Flows?
IdeaLeaves and cycles, direct recursion
Key Observation

Any graph where each node has out-degree 1 is a collection of cycles with trees hanging off them.

Draw from Experience

I knew this structure from prior problems — but you can also [Draw a Picture] and [Examine Examples] to convince yourself: keep following the out-edges from any node and you must eventually revisit a node. That's a cycle.

Key Observation

If any leaf (a node with no incoming edges) is not special, the selection is bad: nothing can reach a leaf, so every leaf must be special.

Key Observation

Symmetrically, if some component is a pure cycle (no trees attached), then at least one node on that cycle must be special — otherwise the whole component is unreachable.

At this point the problem still seemed really hard given the O(nlogn)O(n \log n) constraint.

Relax the Constraints

Ignore the O(nlogn)O(n \log n) requirement — can I solve this at all, in O(n2)O(n^2) or O(n3)O(n^3), to get a feel?

Draw from Experience

Problems like this usually work by deciding what happens to node nn, then recursing on the graph with n1n-1 nodes.

This leads to a recurrence. Let F(n,m,k)F(n,m,k) be the count over all functional graphs with nn nodes, mm special nodes, and kk leaves. Then, splitting on what the nn-th node is:

F(n,m,k) = {n'th is a leaf, pointing to a previous leaf}
         + {n'th is a leaf, pointing to a previous non-leaf}
         + {n'th is not a leaf}
         = F(n-1,m,k) * k  +  F(n-1,m-1,k-1) * (n-k-1)  +  ...

To be honest, I couldn't figure out the rest of the recurrence for the case where node nn is not a leaf. We have some good core ideas, but this recurrence is too complex to work with.

IdeaPrüfer sequences — what if it were a tree?No Solution
Problem Simplification

The cycles were confusing me, so I started wondering: could I solve this on a tree instead of a loopy functional graph? How many trees are there with nn nodes and kk leaves?

Ask for Help

After Googling a little, I found this is related to Prüfer sequences.

Definition.

A Prüfer sequence encodes a labeled tree on nn nodes as a sequence of n2n-2 numbers: repeatedly take the smallest-numbered leaf, remove it, and record its neighbor's label, until 2 nodes remain.

These sequences are a bijection: every sequence of n2n-2 numbers from 1..n1..n corresponds to exactly one labeled tree, giving Cayley's formula nn2n^{n-2} for the number of labeled trees. For rooted trees the same procedure runs until only the root remains, giving sequences of length n1n-1 and nn1n^{n-1} rooted trees.

To count trees by their number of leaves, ask: can you read off the leaves from the Prüfer sequence?

Lemma.

In the rooted-tree encoding, the leaves of the tree are exactly the labels that do not appear in the Prüfer sequence — a leaf is never recorded as anyone's parent, while every internal node must be.

So let T(n,k)T(n,k) be the number of rooted trees with nn nodes and kk leaves — equivalently, the number of sequences of length n1n-1 over 1..n1..n in which exactly kk labels never appear.

Problem Transformation

Pretend we have nkn-k boxes — the labels that do appear. We must assign each of the n1n-1 sequence slots to one of the boxes so that no box is empty. Partitioning items into non-empty groups is exactly the Stirling numbers of the second kind S(n,k)S(n,k) — something I recognized from experience.

T(n,k)=(nk)S(n1,nk)(nk)!T(n,k) = \binom{n}{k} \cdot S(n-1,\, n-k) \cdot (n-k)!

(choose which kk labels are leaves; partition the n1n-1 slots into nkn-k non-empty groups; assign the groups to actual labels.)

If we could compute the Stirling numbers, the tree version of the problem would follow by summing over the number of leaves kk, forcing all leaves to be special and choosing the remaining mkm-k special nodes freely:

Goodtrees(n,m)=k=1nT(n,k)(nkmk)=k=1n(nk)S(n1,nk)(nk)!(nkmk)\text{Good}_{\text{trees}}(n,m) = \sum_{k=1}^{n} T(n,k)\binom{n-k}{m-k} = \sum_{k=1}^{n} \binom{n}{k} S(n-1, n-k)\,(n-k)!\,\binom{n-k}{m-k}

(Factorials up to 10610^6 and their modular inverses can be precomputed, making each binomial O(1)O(1).)

So the hard part is computing the Stirling numbers. There are two classic routes:

AlgorithmStirling numbers via recursion

Consider item nn: either it is a singleton subset, or it joins one of the kk existing subsets:

S(n,k) = S(n-1,k-1) + k * S(n-1,k)

Correct, but O(n2)O(n^2) time and space — too slow here.

AlgorithmStirling numbers via inclusion-exclusion

Number the kk boxes and assign each of the nn items a box: knk^n ways, but some boxes may be empty. Let AiA_i be the assignments where box ii is empty; subtract the union via inclusion-exclusion (see the Aside below), then divide by k!k! to unlabel the boxes:

S(n,k)=1k!j=0k(1)j(kj)(kj)nS(n,k) = \frac{1}{k!} \sum_{j=0}^{k} (-1)^j \binom{k}{j} (k-j)^n

Defining Aj:=(1)jA_j := (-1)^j and Bj:=(kj)jnB_j := \binom{k}{j} j^n, both computable for all jj in O(n)O(n), the values S(n,k)S(n,k) for all kk at once form a convolution ABA * B — computable in O(nlogn)O(n \log n) with the Fast Fourier Transform (FFT).

A note on that last step: FFT is a relatively involved algorithm, and in another world I'd build it up here the way I do inclusion-exclusion below — but since we're about to move on from trees entirely, that would be a distraction. I did try to simplify Goodtrees\text{Good}_{\text{trees}} to avoid the FFT, but the double sum doesn't separate: the inner index stays coupled to kk through the (nkj)n(n-k-j)^n term, which is exactly the shape a convolution exists to handle.

Problem Generalization

With some work this extends to forests by adding a dummy root node n+1n+1. But I need functional graphs, not forests — good time to move on.

Observation.

We can use bijections from number sequences to trees (or forests, or graphs), and count sequences with certain properties instead of counting graphs directly.

Observation.

Inclusion-exclusion can turn these counting problems into explicit closed-form sums over one index k=1..nk = 1..n — which is O(n)O(n) once factorials are precomputed.

AsideFormalizing Inclusion-Exclusion

A technique used briefly above, and heavily below, is inclusion-exclusion. I generally understand it, but it's worth formalizing.

Let AA and BB be two sets of outcomes — possibly overlapping. To count outcomes where at least one of them occurs:

Lemma.

AB=A+BAB|A \cup B| = |A| + |B| - |A \cap B|

Applying this repeatedly generalizes to more sets:

ABC=(AB)C=AB+C(AB)C=A+B+CABACBC+ABC\begin{aligned} |A \cup B \cup C| &= |(A \cup B) \cup C| \\ &= |A \cup B| + |C| - |(A \cup B) \cap C| \\ &= |A| + |B| + |C| - |A \cap B| - |A \cap C| - |B \cap C| + |A \cap B \cap C| \end{aligned}

and in general, for sets A1,,AnA_1, \ldots, A_n:

iAi=iAii<jAiAj+i<j<kAiAjAk\left| \bigcup_i A_i \right| = \sum_i |A_i| - \sum_{i<j} |A_i \cap A_j| + \sum_{i<j<k} |A_i \cap A_j \cap A_k| - \cdots

The sign alternates with the number of sets intersected.

Why is this useful? In many problems, counting the intersection (AA AND BB AND CC) is far easier than counting the union (AA OR BB OR CC). If you can write a simple formula for the intersection of any subset of your sets, inclusion-exclusion hands you the union.

Work an Example

In the Stirling-number problem: let AiA_i = assignments where box ii is empty. We want no box empty, i.e. knA1Akk^n - |A_1 \cup \cdots \cup A_k|. Any intersection of jj of these sets is trivial to count — it's just (kj)n(k-j)^n, assignments avoiding jj boxes — which yields the formula above.

Lesson

The trick to inclusion-exclusion is choosing the events so that describing any intersection of them is easy.

IdeaGeneralizing to functional graphs

Idea 2 was insightful but only handles trees. Functional graphs have cycles. It turns out the core approach — write the graph as a sequence and count sequences with the right properties — still works, together with inclusion-exclusion.

Instead of Prüfer sequences, work with what we've got directly: each node points to exactly one other node, so the sequence (f1,f2,,fn)(f_1, f_2, \ldots, f_n) — where fif_i is the node that ii points to, fiif_i \neq i — uniquely determines the functional graph. There are (n1)n(n-1)^n such sequences.

Key Observation

A node is a leaf exactly when it never appears in the sequence (f1,,fn)(f_1, \ldots, f_n) — the same trick as reading leaves off a Prüfer sequence, applied to the functional graph's own pointer sequence. So we can do inclusion-exclusion directly on "node ii never appears."

By symmetry, first choose the mm special nodes: (nm)\binom{n}{m} ways; say they are nodes 1..m1..m. A selection fails on leaves if some non-special node is a leaf. Let AiA_i (for i>mi > m) be the set of sequences where node ii is a leaf.

For a fixed set of kk forced leaves, count the sequences: each forced leaf must point somewhere (but not to itself or another forced leaf, which must stay leaves) — (nk)(n-k) choices each — and each of the other nkn-k nodes must avoid itself and all kk leaves — (n1k)(n-1-k) choices each. So by inclusion-exclusion, the number of sequences with no bad leaves is:

k=0nm(1)k(nmk)(nk)k(n1k)nk\sum_{k=0}^{n-m} (-1)^k \binom{n-m}{k} (n-k)^k (n-1-k)^{n-k}

and the candidate answer is (nm)\binom{n}{m} times that. We're making a ton of progress — but this is still wrong: it ignores the pure cycles. A component that is a bare cycle with no special node on it is unreachable, and nothing above accounts for that.

Let's tackle that next.

IdeaPure cycles and derangements
Draw from Experience

If the graph consisted of only pure cycles, it would look exactly like a permutation — any permutation decomposes into disjoint cycles. Cycle-counting on permutations is the territory of the (unsigned) Stirling numbers of the first kind. Useful, or a distraction...

Since self-loops are forbidden, we need permutations with no fixed points — these are called derangements. (The first-kind Stirling numbers aren't directly applicable.)

Definition.

From here on, derangement means a permutation with no fixed points — equivalently, a functional graph consisting only of pure cycles of length 2\geq 2. The equivalence: in a permutation every node has out-degree 1 and in-degree 1, so the graph is exactly a disjoint union of cycles, and "no fixed points" is precisely "no self-loops."

It turns out derangements are counted by — you guessed it — inclusion-exclusion. Let AiA_i be the permutations where element ii is a fixed point. Then:

D(n)=n!iAi=j=0n(1)j(nj)(nj)!=n!j=0n(1)jj!D(n) = n! - \left|\bigcup_i A_i\right| = \sum_{j=0}^{n} (-1)^j \binom{n}{j} (n-j)! = n! \sum_{j=0}^{n} \frac{(-1)^j}{j!}

(the middle step expands (nj)(nj)!=n!/j!\binom{n}{j}(n-j)! = n!/j!). This is computable in O(n)O(n) — or all values D(0..n)D(0..n) in one O(n)O(n) sweep.

Ask for Help

Side note: that last sum is the power series of exe^x at x=1x = -1, so D(n)n!/eD(n) \approx n!/e — in fact D(n)=round(n!/e)D(n) = \text{round}(n!/e) exactly, for all n1n \geq 1. (We work modulo 998244353998244353, so we use the sum, not the rounding trick.)

Observation.

Using inclusion-exclusion, all derangement counts D(0..n)D(0..n) can be precomputed in O(n)O(n) total time.

This counts the pure-cycle graphs. But our problem also chooses mm special nodes, and demands every cycle contain one. So the next question is how to count derangement–selection pairs where no cycle is missed — still on pure cycles only, which remains a useful stepping stone before combining everything.

IdeaCounting good selections on pure cycles

Idea 4 counts pure-cycle graphs; now, on a graph of only pure cycles (a derangement), count selections of mm special nodes such that every cycle contains at least one of them. This is the part that stumped me.

Ask for Help

I was stuck here for a while and looked at the solution — so this section is a reverse-engineering of the logic. I completely missed the key observation, and I think you'll find it fun to reconstruct.

Given how far we've come, we want inclusion-exclusion. But on what events?

My first attempt: let AiA_i be the derangement–selection pairs where node ii is trapped in a bad cycle (one containing no special node). Then the answer would be D(n)A1AnD(n) - |A_1 \cup \cdots \cup A_n|... and this is where I got stuck. I could not write down clean formulas for the intersections AiAj|A_i \cap A_j \cap \cdots|.

Observation.

Inclusion-exclusion only works when you have a clean way to count the intersections. If the intersections are gnarly, you've chosen the wrong events.

Key Question

If we want to penalize "bad cycles," what should the events be?

Key Observation

The cycles ARE the events. Fix the mm special nodes. For each possible cycle CC containing no special node (a bad candidate), let XCX_C be the set of derangements in which CC appears as one of the cycles. There may be a gazillion candidate cycles, but the answer is simply D(n)XC1XC2D(n) - |X_{C_1} \cup X_{C_2} \cup \cdots| over all bad candidates — and these intersections are easy: once you decide that specific cycles appear, all their nodes' edges are fixed, and the remaining nodes just form a derangement among themselves.

Concretely: an intersection of cc disjoint bad cycles covering jj nodes fixes those jj nodes entirely, and the other njn-j nodes can be deranged freely among themselves: D(nj)D(n-j) ways. First choose which jj non-special nodes sit in the bad cycles — (nmj)\binom{n-m}{j} ways — then let Wj,cW_{j,c} count the ways to arrange those jj nodes into exactly cc cycles (each of length 2\geq 2). Inclusion-exclusion gives:

Goodcycles(n,m)=(nm)j=0nmc=0j(1)c(nmj)Wj,cD(nj)\text{Good}_{\text{cycles}}(n,m) = \binom{n}{m} \sum_{j=0}^{n-m} \sum_{c=0}^{j} (-1)^{c} \binom{n-m}{j} W_{j,c}\, D(n-j)

Pull everything independent of cc out of the inner sum:

=(nm)j=0nm(nmj)D(nj)[c=0j(1)cWj,c]= \binom{n}{m} \sum_{j=0}^{n-m} \binom{n-m}{j} D(n-j) \left[ \sum_{c=0}^{j} (-1)^{c} W_{j,c} \right]

If we could kill that inner sum, we'd have a single O(n)O(n) loop. First, Wj,cW_{j,c} satisfies a recursion (good ol' fashioned recursion — no inclusion-exclusion needed): let 2\ell \geq 2 be the length of the cycle containing the jj-th node — choose its 1\ell - 1 companions and arrange the cycle:

Wj,c==2j(j11)(1)!  Wj,c1=(j1)!r=0j2Wr,c1r!W_{j,c} = \sum_{\ell=2}^{j} \binom{j-1}{\ell-1} (\ell-1)!\; W_{j-\ell,\,c-1} = (j-1)! \sum_{r=0}^{j-2} \frac{W_{r,\,c-1}}{r!}

Not obviously simpler — but substitute it into the alternating sum. Writing Φ(j):=c(1)cWj,c\Phi(j) := \sum_{c} (-1)^c W_{j,c}:

Φ(j)=c(1)c(j1)!r=0j2Wr,c1r!=(j1)!r=0j2Φ(r)r!\Phi(j) = \sum_{c} (-1)^{c} (j-1)! \sum_{r=0}^{j-2} \frac{W_{r,c-1}}{r!} = -(j-1)! \sum_{r=0}^{j-2} \frac{\Phi(r)}{r!}
Key Observation

Φ(j)=c=0j(1)cWj,c=1j\Phi(j) = \sum_{c=0}^{j} (-1)^c W_{j,c} = 1 - j for all j0j \geq 0.

Proof.

Induction on jj. Base cases: Φ(0)=W0,0=1=10\Phi(0) = W_{0,0} = 1 = 1-0 (the empty arrangement), and Φ(1)=0=11\Phi(1) = 0 = 1-1 (one node can't form a cycle of length 2\geq 2). For j2j \geq 2, assume Φ(r)=1r\Phi(r) = 1-r for all r<jr < j. The summand telescopes: for r1r \geq 1,

1rr!=1r!rr!=1r!1(r1)!\frac{1-r}{r!} = \frac{1}{r!} - \frac{r}{r!} = \frac{1}{r!} - \frac{1}{(r-1)!}

so

r=0j21rr!=1+(1(j2)!10!)=1(j2)!\sum_{r=0}^{j-2} \frac{1-r}{r!} = 1 + \left(\frac{1}{(j-2)!} - \frac{1}{0!}\right) = \frac{1}{(j-2)!}

and therefore

Φ(j)=(j1)!1(j2)!=(j1)=1j.\Phi(j) = -(j-1)! \cdot \frac{1}{(j-2)!} = -(j-1) = 1-j.

So the pure-cycle answer collapses to a single sum:

Goodcycles(n,m)=(nm)j=0nm(nmj)D(nj)(1j)\text{Good}_{\text{cycles}}(n,m) = \binom{n}{m} \sum_{j=0}^{n-m} \binom{n-m}{j}\, D(n-j)\, (1-j)

with derangements and factorials precomputed in O(n)O(n). Notice again: nn and mm are treated as fixed constants; we only sum over jj.

In Idea 3 we got the core idea for components with leaves. Here we got the core idea for cycles. Can we put it all together?

IdeaPutting it all togetherAC

The final solution combines Ideas 3 and 5 into one inclusion-exclusion over all the bad events at once.

Fix nn and mm; choose the mm special nodes ((nm)\binom{n}{m} ways, WLOG nodes 1..m1..m), and represent each graph as its pointer sequence (f1,,fn)(f_1, \ldots, f_n). The bad events:

  • AiA_i for each non-special node ii: node ii is a leaf (appears nowhere in the sequence);
  • XCX_C for each special-free cycle CC: the nodes of CC form exactly that cycle, and nothing outside points into it (a pure bad cycle).

A selection is bad iff at least one of these occurs, so we subtract AiXC\left| \bigcup A_i \cup \bigcup X_C \right| from (n1)n(n-1)^n via inclusion-exclusion. Consider an intersection with kk leaf-events and cc cycle-events covering jj nodes (sign (1)k+c(-1)^{k+c}):

  • choose the jj nodes for the bad cycles ((nmj)\binom{n-m}{j} ways), then form the cycles (Wj,cW_{j,c} ways) — their edges are now fixed;
  • each of the kk forced leaves points anywhere except itself, the other leaves, and the cycle nodes: (njk)(n-j-k) choices;
  • each of the remaining njkn-j-k free nodes avoids itself, the leaves, and the cycle nodes: (n1jk)(n-1-j-k) choices.
Good(n,m)=(nm)j=0nm(nmj)k=0nmj(1)k(nmjk)(n1jk)njk(njk)kc=0j(1)cWj,c\text{Good}(n,m) = \binom{n}{m} \sum_{j=0}^{n-m} \binom{n-m}{j} \sum_{k=0}^{n-m-j} (-1)^k \binom{n-m-j}{k} (n-1-j-k)^{n-j-k} (n-j-k)^k \sum_{c=0}^{j} (-1)^{c} W_{j,c}

Now simplify, in three moves:

  1. Replace the inner cc-sum with 1j1-j (Key Observation 6).
  2. Substitute a:=j+ka := j+k and regroup — the summand depends on j,kj,k only through aa and the leftover (1j)(1-j), and the binomials merge as (nmj)(nmjk)=(nma)(ak)\binom{n-m}{j}\binom{n-m-j}{k} = \binom{n-m}{a}\binom{a}{k}.
  3. Pull the aa-only factors out of the inner sum.
Good(n,m)=(nm)a=0nm(nma)(n1a)nak=0a(1)k(ak)(na)k(1(ak))\text{Good}(n,m) = \binom{n}{m} \sum_{a=0}^{n-m} \binom{n-m}{a} (n-1-a)^{n-a} \sum_{k=0}^{a} (-1)^k \binom{a}{k} (n-a)^k \left(1-(a-k)\right)

Split the inner sum using 1(ak)=1a+k1-(a-k) = 1 - a + k into a plain part and an (ak)(a-k)-weighted part. Both collapse:

Key Observation

By the Binomial Theorem (x+y)n=k=0n(nk)xnkyk(x+y)^n = \sum_{k=0}^{n} \binom{n}{k} x^{n-k} y^k with x=1x = 1, y=(na)y = -(n-a):

k=0a(1)k(ak)(na)k=(1+an)a\sum_{k=0}^{a} (-1)^k \binom{a}{k} (n-a)^k = (1 + a - n)^a

and by differentiating the Binomial Theorem in xx — giving n(x+y)n1=k(nk)(nk)xnk1ykn(x+y)^{n-1} = \sum_{k} \binom{n}{k}(n-k)\,x^{n-k-1} y^k — the weighted sum collapses too:

k=0a(1)k(ak)(na)k(ak)=a(1+an)a1\sum_{k=0}^{a} (-1)^k \binom{a}{k} (n-a)^k (a-k) = a\,(1+a-n)^{a-1}
Draw from Experience

The binomial theorem is standard; the derivative trick — differentiate a known identity to collapse an index-weighted sum — is one I'd seen before in generating-function problems, and [Write It Out] is what surfaced it here.

Substituting both back:

Good(n,m)=(nm)a=0nm(nma)(n1a)na[(1+an)aa(1+an)a1]\text{Good}(n,m) = \binom{n}{m} \sum_{a=0}^{n-m} \binom{n-m}{a} (n-1-a)^{n-a} \left[ (1+a-n)^a - a(1+a-n)^{a-1} \right]

Factor the bracket: (1+an)a1[(1+an)a]=(1n)(1+an)a1(1+a-n)^{a-1}\left[(1+a-n) - a\right] = (1-n)(1+a-n)^{a-1}, and since (1+an)=(n1a)(1+a-n) = -(n-1-a), we get (1+an)a1=(1)a1(n1a)a1(1+a-n)^{a-1} = (-1)^{a-1}(n-1-a)^{a-1}, which merges with the (n1a)na(n-1-a)^{n-a} into a single power:

  Good(n,m)=(nm)(n1)a=0nm(1)a(nma)(n1a)n1  \boxed{\;\text{Good}(n,m) = \binom{n}{m}\,(n-1) \sum_{a=0}^{n-m} (-1)^{a} \binom{n-m}{a}\, (n-1-a)^{n-1}\;}

After the inclusion-exclusion miraculously telescopes and simplifies, we sum over a single index aa, treating nn and mm as constants, using precomputed factorials and fast exponentiation for (n1a)n1(n-1-a)^{n-1}. Total: O(nlogn)O(n \log n) (the log\log from the modular exponentiations).

Review

The number of good (graph, selection) pairs, modulo 998244353998244353, is

Good(n,m)=(nm)(n1)a=0nm(1)a(nma)(n1a)n1\text{Good}(n,m) = \binom{n}{m}\,(n-1) \sum_{a=0}^{n-m} (-1)^{a} \binom{n-m}{a}\, (n-1-a)^{n-1}

computable in O(nlogn)O(n \log n). The path there, in key observations:

  1. Structure. A functional graph is cycles with trees attached. A selection is good iff every leaf is special and every pure cycle contains a special node. [1][2][3]
  2. Sequences, not graphs. Encode each graph as its pointer sequence (f1,,fn)(f_1, \ldots, f_n); a node is a leaf iff its label never appears in the sequence. [4]
  3. Inclusion-exclusion needs countable intersections. Choose the events so that intersecting any subset of them is easy to count.
  4. The cycles are the events. One event per special-free candidate cycle ("this exact cycle appears, untouched") freezes its nodes and leaves a clean sub-problem — intersections become trivial, even combined with the leaf events. [5]
  5. The master sum. Intersecting kk leaf-events with cc bad cycles covering jj nodes — where Wj,cW_{j,c} counts the ways to arrange jj chosen nodes into exactly cc cycles of length 2\geq 2 — gives:
(nm)j(nmj)k(1)k(nmjk)(n1jk)njk(njk)kc(1)cWj,c\binom{n}{m} \sum_{j} \binom{n-m}{j} \sum_{k} (-1)^k \binom{n-m-j}{k} (n-1-j-k)^{n-j-k} (n-j-k)^k \sum_{c} (-1)^{c} W_{j,c}
  1. The alternating cycle-sum collapses: c(1)cWj,c=1j\sum_c (-1)^c W_{j,c} = 1-j, by a telescoping induction. [6]
  2. The binomial theorem — and its derivative — kill the remaining inner sum, leaving the single-sum formula above. [7]

Pseudocode:

MAXN = 10**6 + 5
PRIME = 998244353
 
# O(MAXN) precomputation
fact = [1] * MAXN
for i in range(1, MAXN):
    fact[i] = fact[i-1] * i % PRIME
invfact = [modinv(f) for f in fact]   # modinv via pow(f, PRIME-2, PRIME)
 
def choose(n, k):
    if k < 0 or k > n: return 0
    return fact[n] * invfact[k] % PRIME * invfact[n-k] % PRIME
 
def solve(n, m):
    ans = 0
    for a in range(0, n - m + 1):
        term = choose(n - m, a) * pow(n - 1 - a, n - 1, PRIME) % PRIME
        ans = (ans - term if a % 2 else ans + term) % PRIME
    ans = ans * (n - 1) % PRIME
    ans = ans * choose(n, m) % PRIME
    return ans

References

Learning points. In the end this problem was an exercise in inclusion-exclusion, and in being very careful about how you count and decompose the sets.

I got quickly to "look at the leaves and the pure cycles," and tried solving them separately — then got completely stumped on the pure cycles. Part of it was that I kept looking for a recursion on the mm-th or nn-th node, but the recursion was tricky to get right, if it exists at all. Just as with Stirling numbers of the second kind, some counting problems admit both a recursion and an inclusion-exclusion formula — and they have very different computational profiles.

Inclusion-exclusion works when you have an easy time intersecting interesting configurations ABC|A \cap B \cap C| but a hard time with the union ABC|A \cup B \cup C|. Overlapping, conflicting configurations are fine — as long as every subset of events with a known "size" jj has a countable intersection, the machinery (1)j(-1)^j |\cdots| does the rest.

The hardest part for me was recognizing how to run inclusion-exclusion on the pure cycles. I kept choosing "number of nodes trapped in bad cycles" as the quantity to sum over, and no formula worked — there was no clean way to AND together "these particular nodes are in bad cycles." The aha came from making the cycles themselves the events: once a cycle is required to appear, its nodes are frozen and everything else derangles freely, so intersections become easy — even when combined with the leaf events. The resulting sums looked terrifying, then telescoped and collapsed.

I don't think it will always be that clean — but sometimes you just have to [Write It Out], and watch the formula simplify. Notably, nn and mm factored out as constants throughout: we never needed the answer for all (n,m)(n,m), just one final sum over a single index.

I feel I learned a lot about inclusion-exclusion from this problem — and about how seemingly intractable counting problems fall apart once you pick the right events.

Topics: inclusion-exclusion · permutations, derangements, cycle notation · combinatorics, binomial coefficients · recursion & induction · modular arithmetic · fast exponentiation

Related: Stirling numbers (first & second kind) · Prüfer sequences & Cayley's formula · counting labeled trees by leaves