![]() |
VOOZH | about |
Given a connected graph with N nodes and N-1 bidirectional edges given by a 2D array edges[][], such that edges[i] = {u, v, w} states that there is a bidirectional edge between node u and node v with a weight of w. The task is to answer Q queries such that for each query, query[i] = {u, v, w} print "1" if adding a new edge between node u and node v with a weight w will lead to a better MST, else print "0".
Note: All queries are independent of each other.
Examples:
Input: N = 5, edges[][] = {{1, 2, 2}, {1, 3, 3}, {3, 4, 5}, {3, 5, 4}}, Q = 2, query[][] = {{1, 4, 2}, {4, 5, 8}}
Output: 1 0
Explanation:
- In the first query {1, 4, 2}, if we remove the edge from node 3 to node 4 and then add {1, 4, 2}, then we can reduce the total weight by 3 units.
- In the second query, adding the edge {4, 5, 8} will not reduce the minimum cost of MST.
Input: N = 3, edges[][] = {{1, 2, 5}, {1, 3, 6}}, Q = 2, query[][] = {{2, 3, 2}, {2, 3, 12}}
Output: 1 0
Explanation:
- In the first query, if we remove the edge from node 1 and 3 and then add the edge {2, 3, 2}, then we can reduce the total weight by 4 units.
- In the second query, adding the edge {2, 3, 12} will not reduce the minimum cost of MST.
Approach: To solve the problem, follow the below idea:
Since in every query, we are given an edge and we need to find whether adding this new edge to the graph will reduce the cost of MST, so adding an edge will result in a cycle and in order to decrease the cost of MST, this new edge should have smaller weight as compared to maximum weighted edge among all the edges in the cycle.
Let's say we add an edge between (u, v) with a weight w and node u and v have lca(u, v) as L, so to reduce the cost of MST, w < max weighted edge in the cycle. To find the max weighted edge in the cycle, we can find the max weighted edge from node L to node u and from node L to node v. The maximum node among both paths will be the max weighted edge in the cycle.
To find the lca and the maximum weighted edge efficiently for each query, we can use Binary Lifting to store the ancestors (LCA[][]) as well as the maximum weighted edge between node and ancestors (MWE[][]).
- LCA[i][j] will store the (2 ^ j)th ancestor of node i
- MWE[i][j] will store the maximum weighted edge from node i to (2 ^ j)th ancestor of node i.
In this way, we can find the LCA of two nodes and the maximum weighted edge in the cycle in log(N) time only.
Step-by-step algorithm:
Below is the implementation of the algorithm:
1 0
Time complexity: O(N * log(N) + Q * (logN)), where N is the number of nodes and Q is the number of queries.
Auxiliary Space: O(N * log(N)), because of LCA[][] and MWE[][] table.