简体   繁体   English

查找访问树的所有节点的最低成本

[英]Find minimum cost to visit all nodes of a tree

Given the root of a tree where each edge has an associated cost. 给定树的根,其中每个边具有相关的成本。 Find the minimum cost to visit every node of the tree. 找到访问树的每个节点的最低成本。

A recursive solution that came to my mind is: 我想到的一个递归解决方案是:

  1. base case when node is a leaf return 0. 当节点是叶返回0时的基本情况。
  2. for every child c of the node recursively compute the cost. 对于节点的每个子节点c递归地计算成本。
  3. add up all those cost and also add the edge cost twice from node to child twice(as we need to backtrack). 将所有这些成本加起来,并且从节点到子节点两次添加边缘成本两次(因为我们需要回溯)。
  4. subtract the edge cost of the child that has maximum cost.("greedy" - we don't want to backtrack from the child that has maximum cost). 减去具有最大成本的孩子的边缘成本。(“贪婪” - 我们不想从具有最大成本的孩子回溯)。

Is this approach correct? 这种方法是否正确?

Is there a better way to solve the problem? 有没有更好的方法来解决这个问题?

  1. Visit all subtree from a node and returns to the node, it will cost all edges * 2 which belongs to that subtree. 从节点访问所有子树并返回到节点,它将花费属于该子树的所有edges * 2
  2. So we should find a path in the tree which the cost of the path is maximum. 所以我们应该在树中找到路径成本最大的路径。 We just go through the path, and if the we meet some nodes which is not in the path, we just visit it and returns . 我们只是通过路径,如果我们遇到一些不在路径中的节点,我们只是访问它并返回 So The edge in the path will visit only once, and the remain edges will visit twice. 因此路径中的边将只访问一次,剩余边将访问两次。
  3. How to find the path with maximum cost? 如何找到最高成本的路径? Since it's a tree, you can find it recursively. 因为它是一棵树,你可以递归地找到它。

The answer should be: 答案应该是:

sum(cost(edge)*2) - sum(edge which in the path)

I checked your solution, I think it's wrong(If I misunderstand your solution, please leave a comment): 我检查了你的解决方案,我认为这是错误的(如果我误解了你的解决方案,请发表评论):

subtract the edge cost of the child that has maximum cost.("greedy" - we > don't want to backtrack from the child that has maximum cost). 减去具有最高成本的孩子的边缘成本。(“贪婪” - 我们>不想具有最高成本的孩子回溯 )。

That child will be a tree, and some edges must visit twice. 那个孩子将是一棵树,一些边缘必须访问两次。 For example: 例如:

    A
   / \
  B   C
 / \
D   E

You can't visit that subtree all edges once to visit all nodes. 您无法访问该子树所有边缘一次访问所有节点。

1- All the nodes-paths will be visited twice except the last leaf node. 1-除最后一个叶节点外,将访问所有节点路径两次。

2- We will need to find out which leaf node has the highest cost attached to visit root node. 2-我们需要找出哪个叶子节点附加了最高成本才能访问根节点。

3- once we find this we will need to make our traversal such that this leaf node is the last visited node. 3-一旦我们发现这一点,我们将需要进行遍历,使得该叶节点是最后访问的节点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM