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

Автор antivenom, 9 лет назад, По-английски

So question is something like this- "We are given a tree(weighted) and we have to find longest path in the tree and number of all such possible paths ".Number of nodes is of order (<=10^4).

If I am not wrong part 1 can be done using two dfs(please point me if it is wrong).For the second parth I thought it must be some dynamic programming but could not get to any solution.Help me to find "How many such possible path(with longest distance) exist in the tree" ?

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

»
9 лет назад, # |
  Проголосовать: нравится +3 Проголосовать: не нравится

Yes, it could be done using two DFS. But for the second question do you mean the number of paths which has a length equal to the longest path or the number of paths in general?

»
9 лет назад, # |
  Проголосовать: нравится -10 Проголосовать: не нравится

nojefndlamefneqldmqefnqelfd;m

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

if weights greater that zero any longest path should contain at least one node from first one (it can be found by two dfs).

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

Let's select node #1 as a root and hang the tree from it, so that every other node will get a parent. Now for every node we can calculate the distance to its farthest descendant (which of course will be a leaf), let's call it a height of current node. And also we will calculate the number of such leafs providing max height for current node.

For all leafs the height will be 0 and the count will be 1 (empty path containing only the leaf itself). For any other node, if we have already calculated heights for its childs then for current node the height can be calculated using heights of all childs and edge weights connecting them to current node.

After that we will be able to calculate the number of longest paths which contain current node and fully belong to its subtree. To do that we will take two childs providing max heights for current node connect them through it. It is possible to calculate the number of such paths in O(N * logN) by sorting children and multiplying their quantities by the sum of quantities of other childs which provide the max answer when paired with the current one. If current node has only one child, then we will just take the max height of that child and add the edge weight connecting it to current node.