I reading about derangements, and the following question came to my mind.
Suppose in an office, there work 5 teams, each consisting of 1 head and 3 staff (so there is a total of 15 staff). If the company wants to rearrange the staffs such that each staff is assigned to a different head, how many ways can it be done?
I thought about this, but I don't understand how this can be solved. Can anyone help?
The Python code below counts the number of possible assignments for $m$ teams of size $n$. It recursively assigns staff members to new teams, keeping track of how many empty slots and unassigned members there are for each team, and aggressively caching partial results.
For $n=1$, this is just the number of derangements of $m$ elements. For $n>1$, many of these sequences appear to be in the OEIS as "card-matching numbers" or "dinner-diner matching numbers". For instance, your case (teams of size $3$) appears as OEIS:A059703. The answer to the original question ($5$ teams of size $3$) is $6699824$.
Note that a decent approximation can be obtained by counting the number of ways to assign the staff to the $5$ teams in sets of $3$ (this is $15! / (3!)^5$), and then multiplying this by a rough probability that no one is assigned to his old team (each person is on a new team with probability $4/5$, so we can try $(4/5)^{15}$ for the overall probability). This gives $$ \frac{15!}{(3!)^5}\left(\frac{4}{5}\right)^{15} \approx 5900000, $$ or about $10\%$ less than the correct figure.