Skip to content
Advertisement

Add new edge to Graph and check if total weight is reduced

I’m new to Graphs and I’m trying to solve this problem in Java:

Given a Graph with N nodes and N-1 weighted bidirectional edges, the algorithm must respond YES if a new edge ‘q’ allows to reduce the overall weight of the graph, NO otherwise.

The edge ‘q’ satisfies this condition if there is an edge ‘e’ such that it is possible to replace ‘e’ with ‘q’ leaving the graph connected and decreasing its overall weight.

I implemented the graph with adjacency list:

JavaScript

Edge class:

JavaScript

and a Graph class:

JavaScript

Is there an algorithm that I can use to solve the problem?

Advertisement

Answer

Given a Graph with N nodes and N-1 weighted bidirectional edges,

Then the Graph is a tree. (Assuming the Graph is connected.) A useful property of trees is that for any two nodes s and t in the tree, there exists a single unique (simple) path between them.

the algorithm must respond YES if a new edge ‘q’ allows to reduce the overall weight of the graph, NO otherwise.

Adding a new edge between two nodes (say, s and t) in a tree creates a cycle. Removing any edge in this new cycle will create a new (connected) graph that is also a tree.

The edge ‘q’ satisfies this condition if there is an edge ‘e’ such that it is possible to replace ‘e’ with ‘q’ leaving the graph connected and decreasing its overall weight.

This condition can only be satisfied if there exists one or more edges in the path from s to t (or t to s) whose weight is greater than the weight of the new edge q. If there are multiple such edges, any of them may be replaced.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement