geniucos's blog

By geniucos, history, 8 years ago, In English

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.

  • Vote: I like it
  • +34
  • Vote: I do not like it

»
8 years ago, # |
  Vote: I like it +41 Vote: I do not like it

I have recently solved this problem, here is my code: http://ideone.com/ENhisf

Main 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)).

  • »
    »
    8 years ago, # ^ |
    Rev. 4   Vote: I like it 0 Vote: I do not like it

    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.

    • »
      »
      »
      8 years ago, # ^ |
      Rev. 3   Vote: I like it +3 Vote: I do not like it

      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.

      • »
        »
        »
        »
        8 years ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        Counting unlabeled trees is not as easy as counting labeled trees.

    • »
      »
      »
      8 years ago, # ^ |
        Vote: I like it +9 Vote: I do not like it

      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.