---
id: 804
lang: en
translation_of: index.md
source_sha256: bfafb595ac5892571d4f9975bad653a26f8ecdeb2837299feb0b677e9b4f1404
title: "CH3602: Counting Swaps — Solution"
description: "This is a good problem that uses graph modeling, and you could say it is truly exquisite."
tags: ["OI","Permutations and Combinations","Counting","Counting DP"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes: []
---

## Main Idea

This is a good problem: it uses graph modeling, and you could say it is truly exquisite.

For each $i$, connect a directed edge between it and $arr[i]$. For example, for the sequence $2\ 1\ 4\ 3$:

![graph1](media/graph.png)

We can find the $k$ cycles by DFS coloring, and denote the length of each cycle by $l_i$. We can derive a lemma:

> In the graph, for a cycle of length $n$, the minimum number of steps to turn it into self-loops is $n-1$.

It's exactly this property that lets us define $F[i]$ as the number of ways to turn a cycle of length $i$ into self-loops. Then, based on the idea of splitting, let $T(x,y)$ be the number of ways to split a cycle of length $x+y$ into cycles of lengths $x,y$ respectively. Clearly:

$$
T(x,y) = \begin{cases} \frac{n}{2}, x = y \\ n, x \neq y \end{cases}
$$

So, as usual, we can derive:

$$
F[i] = \sum_{x+y=i} T(x,y)*F[x]*F[y]*\frac{(n-2)!}{(x-1)!(y-1)!}
$$

Let me explain what this formula means: first, enumerate the cases of $x$ and $y$, then multiply by the number of ways for each of the two to become self-loops on its own, i.e. $F[x]*F[y]$. After that, by the multiset permutation formula and the lemma above, the two take $x-1,y-1$ steps respectively, so it's not hard to arrive at that <span class="slang" data-zh="一坨" data-gloss="yī tuó, “a lump, a blob”. Casual, slightly crude word for a big messy chunk of something; here, the formula.">whole lump</span> above.

The answer is $\prod_{i = 1}^k {F_{l_i}} * \frac{(n-k)!}{\prod_{i = 1}^{k}(l_i-1)}$, with time complexity $O(n^2)$. However, through <span class="slang" data-zh="人类智慧" data-gloss="rénlèi zhìhuì, “human wisdom”. OI slang for a solution that hinges on a clever, hard-to-motivate insight rather than a standard technique.">human wisdom</span> and the like, we find that $F[n]=n^{n-2}$, so with fast exponentiation it drops to $O(n \log n)$.

## Code

```cpp
// CH3602.cpp
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int MAX_N = 1e5 + 200, mod = 1e9 + 9;
int T, n, arr[MAX_N], head[MAX_N], current, k, li[MAX_N], vis[MAX_N];
ll level[MAX_N], inv[MAX_N];
struct edge
{
    int to, nxt;
} edges[MAX_N << 1];
void addpath(int src, int dst)
{
    edges[current].to = dst, edges[current].nxt = head[src];
    head[src] = current++;
}
int dfs(int u, int fa)
{
    vis[u] = true;
    for (int i = head[u]; i != -1; i = edges[i].nxt)
        if (edges[i].to != fa)
        {
            if (vis[edges[i].to])
                return 1;
            return dfs(edges[i].to, u) + 1;
        }
    return 1;
}
ll quick_power(ll bas, ll tim)
{
    ll ans = 1;
    while (tim)
    {
        if (tim & 1)
            ans = ans * bas % mod;
        bas = bas * bas % mod;
        tim >>= 1;
    }
    return ans;
}
ll Fn(int n) { return (n == 1) ? 1 : quick_power(n, n - 2); }
int main()
{
    scanf("%d", &T);
    level[0] = inv[0] = 1;
    for (int i = 1; i < MAX_N; i++)
        level[i] = level[i - 1] * i % mod;
    inv[MAX_N - 1] = quick_power(level[MAX_N - 1], mod - 2);
    for (int i = MAX_N - 1; i >= 2; i--)
        inv[i - 1] = inv[i] * i % mod;
    while (T--)
    {
        memset(head, -1, sizeof(head)), current = 0;
        memset(li, 0, sizeof(li)), k = 0;
        memset(vis, 0, sizeof(vis));
        scanf("%d", &n);
        for (int i = 1; i <= n; i++)
            scanf("%d", &arr[i]), addpath(arr[i], i), addpath(i, arr[i]);
        for (int i = 1; i <= n; i++)
            if (!vis[i])
                li[++k] = dfs(i, 0);
        ll ans = 1;
        for (int i = 1; i <= k; i++)
            ans = ans * Fn(li[i]) % mod;
        ans = (ans * level[n - k] % mod);
        for (int i = 1; i <= k; i++)
            ans = ans * inv[li[i] - 1] % mod;
        printf("%lld\n", ans);
        continue;
    }
    return 0;
}
```
