### geniucos's blog

By geniucos, history, 4 years ago, ,

I've been thinking for about 2 months at a problem and I haven't manage to find a solution, so I've decided to ask for your help. The problem is pretty nice. It asks for the number of trees(2 trees are considered different if they are not isomorphs) with N vertices and diameter D. Here you have the link . It was given in Polish Algorithmic Engagements 2008 at the final round and as far as I know there are no written solutions for this kind of contest.

• +34

 » 4 years ago, # |   +41 I have recently solved this problem, here is my code: http://ideone.com/ENhisfMain idea is to observe that every tree has uniquely determined midpoint of all of its diameters, root our tree there (there are basically two cases — odd and even D) and use some dp to count everything. I used 3D dp array dp[n][d][s] which denotes "what is the number of rooted trees with n vertices, depth not larger than d and so that no son's subtree is larger than s" (I believe that last dimension can be omitted (but without changing the complexity)).
•  » » 4 years ago, # ^ | ← Rev. 4 →   0 Thanks a lot :) I'll try to think at this idea. I think I got it.PS: It is very interesting that in this way you can even count the number of trees with N vertices, problem for which I didn't know that there exist a solution.
•  » » » 4 years ago, # ^ | ← Rev. 3 →   +3 You may want to check Prufer sequences. One can use them to show that there are nn - 2 trees.EDIT — sorry, I didn't understand the topic correctly.
•  » » » » 4 years ago, # ^ |   0 Counting unlabeled trees is not as easy as counting labeled trees.
•  » » » 4 years ago, # ^ |   +9 You may be interested in solving this problem also: https://www.facebook.com/hackercup/problem/553629301337025/ By the way, in that problem you've linked we needed to fix diameter, however if nothing is fixed then we also have a choice of rooting our tree in a centroid which often leads to a simpler code.