简体   繁体   中英

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?

I thought of a solutions thats O(n^2)

For each vertex we start a DFS from it and stop it when the sum gets bigger than C . Since the number of edges is n-1 , that gives us obviously an O(n^2) solution.

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) .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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