TITLE: Is there a Graph theory way to solve this iteration problem
QUESTION [5 upvotes]: This thought came when i was trying to find the number of functions $f(x)$ from $\{1,2,3,4,5\}$ to $\{1,2,3,4,5\}$ that satisfy $f(f(x)) = f(f(f(x)))$ for all $x$ in $\{1,2,3,4,5\}$.  What i did was took cases when only one , two...etc  values of x such that all those are identity functions from that i got the answer as 756 which is correct.  But i was thinking if there was some kind of GT use can be done here  which can solve it more easily than case bash?

REPLY [2 votes]: From @Mike Earnest and @Milten approaches, now I am considering a graph on $\{1,2,3,4,5\}$ made by placing an arrow from $i$ to $j$ if $f(i)=j$, and removing all self-loops. Absolutely we can have no cycles, so this graph is in fact a forest. Adding a vertex $r$ to the graph and having all roots of trees in this graph (that is, $i$ with $f(i)=i$) point to $r$. Then what we want to count is trees on $\{1,2,3,4,5,r\}$ with every vertex a distance of at most $3$ from $r$ (this is equivalent by directing all edges towards $r$). Ignoring the distance condition, Cayley's formula gives that there are $6^4=1296$ trees. We now must subtract the trees with at least one vertex of distance $4$ from $r$. Such trees will have a "backbone" of $5$ consecutive vertices ending at $r$ (say $v_4,v_3,v_2,v_1,r$) and then the 6th vertex will have one of these as its parent. If the parent is $r,v_1,v_2,v_4$ there are $5!$ trees each, and if the parent is $v_3$ there will be $\frac{5!}{2}$ because the 6th vertex and $v_4$ can be swapped. Hence required answer is $1296-120\cdot 4-60 = 756$.