Блог пользователя CrazyCircle

Автор CrazyCircle, история, 4 года назад, По-английски

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?

  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится

»
4 года назад, # |
Rev. 3   Проголосовать: нравится 0 Проголосовать: не нравится

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 года назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    Any solution other than brute force?

    • »
      »
      »
      4 года назад, # ^ |
      Rev. 2   Проголосовать: нравится 0 Проголосовать: не нравится

      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