简体   繁体   English

树图 - 找到多少对顶点,它们之间路径上的边总和为 C

[英]tree graph - find how many pairs of vertices, for which the sum of edges on a path between them is C

I've got a weighted tree graph, where all the weights are positive.我有一个加权树图,其中所有的权重都是正的。 I need an algorithm to solve the following problem.我需要一个算法来解决以下问题。

How many pairs of vertices are there in this graph, for which the sum of the weights of edges between them equals C?这个图中有多少对顶点,它们之间边的权重之和等于 C?

I thought of a solutions thats O(n^2)我想到了一个O(n^2)的解决方案

For each vertex we start a DFS from it and stop it when the sum gets bigger than C .对于每个顶点,我们从它开始一个 DFS,并在总和大于C时停止它。 Since the number of edges is n-1 , that gives us obviously an O(n^2) solution.由于边的数量是n-1 ,这显然给了我们一个O(n^2)解决方案。

But can we do better?但我们能做得更好吗?

For an undirected graph, in terms of theoretic asymptotic complexity - no, you cannot do better, since the number of such pairs could be itself O(n^2) .对于无向图,就理论渐近复杂性而言 - 不,您不能做得更好,因为此类对的数量本身可能是O(n^2)

As an example, take a 'sun/flower' graph:以“太阳/花朵”图为例:

G=(V[union]{x},E)
E = { (x,v) | v in V }
w(e) = 1 (for all edges)

It is easy to see that the graph is indeed a tree.很容易看出该图确实是一棵树。

However, the number of pairs that have distance of exactly 2 is (n-1)(n-2) which is in Omega(n^2) , and thus any algorithm that finds all of them will be Omega(n^2) in this case.但是,距离正好为 2 的对的数量是(n-1)(n-2) ,它在Omega(n^2) ,因此任何找到所有这些的算法都将是Omega(n^2)在这种情况下。

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

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