CrazyCircle's blog

By CrazyCircle, history, 4 years ago, In English

We are given an array A of size n ( n <= 1000) , where A[i] = number of nodes in the level i of the tree.

Given this information, what is the maximum possible diameter of the tree. Can anyone help?

  • Vote: I like it
  • 0
  • Vote: I do not like it

| Write comment?
»
4 years ago, # |
Rev. 3   Vote: I like it 0 Vote: I do not like it

For a brute force solution, try to construct a tree. Then select a random node $$$p$$$. Do the first bfs/dijkstra to get the furthest vertice $$$u$$$ from $$$p$$$. Do the second bfs/dijkstra to get the furthest vertice $$$v$$$ from $$$p$$$. Then $$$u-v$$$ is the furthest pair in tree, hence the diameter of the tree is the distance from $$$u$$$ to $$$v$$$

For your problem, we move from the root of some subtrees to the furthest possible node $$$u$$$ in the left, remove it from the tree and do the same thing with furthest possible node $$$v$$$ in the right. The diameter of the tree is the distance from $$$u$$$ to $$$v$$$

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

    Any solution other than brute force?

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

      The approaching of not attempting to construct such trees are choosing some substree's root and try to lowest leaf $$$u$$$ and erase the path, then do again and get vertice $$$v$$$, then $$$u-v$$$ would be the diameter of that subtree. The maximal over all diameters is diameter of the whole tree (Removing the path from $$$x$$$ to $$$y$$$ means to reduce the number of nodes of $$$a[x], a[x + 1], ..., a[y - 1], a[y]$$$, all by one)

      The number of ways of choosing such subtree is $$$O(n)$$$ and finding diameter in $$$O(n)$$$. But there is still a way to improve this from $$$O(n^2)$$$ solution to linear $$$O(n)$$$ that is to using DP