Explanation
This strategy is known as The Multinomial Theorem.
We are essentially counting how many distinct strings we can make by permuting the letters of the string. Note that if there are repeating characters in the string, permuting those characters in place counts as the same string since letters are indisguinshable.
For example, consider the string , and supposed we denote the 's that appear in the string in order of which they appear, so the original string becomes . One possible permutation is . When we remove these subscripts, these two strings become the same thing.
To account for this, we'll go through each letter which occurs in the string and divide off the number of arrangements among its occurrences. The total number of permutations is . The number of ways a letter can permute is also just the factorial of the number of times it appears in the string.
Implementation
Time Complexity:
C++
#include <bits/stdc++.h>using namespace std;using ll = long long;const ll MOD = 1e9 + 7;const int MAXN = 1e6;array<ll, MAXN + 1> fact; // fact[i] = i! % MODarray<ll, MAXN + 1> inv; // inv[i] = modular inverse of fact[i];// calculate a ^ b (mod m) in log b time
Python
from collections import CounterMAXN = 10**6MOD = 10**9 + 7fac = [0] * (MAXN + 1)inv = [0] * (MAXN + 1)Code Snippet: Combinatorics Functions (from the module) (Click to expand)
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!