![]() |
VOOZH | about |
Given a graph G with N vertices numbered from 1 to N and M undirected edges defined from vertex u to vertex v i.e. [ui, vi]. Each edge has an integer weight [wi] associated with it. You are given Q queries where each query consists of a vertex and an integer weight i.e. [ai, zi]. For each query print the number of vertices it can reach from ai avoiding edges with weights less than equal to zi.
Examples:
Input: N = 4, M = 3, G = {{1, 2, 1}, {1, 3, 2}, {3, 4, 3}}, Q = 3, Q_arr = {{1, 1}, {2, 0}, {3, 1}}
Output: {3, 4, 3}
Explanation:
- Query 1: V = 1, vertices reachable from 1 without traversing through edges with weights <= 1 are 1->3->4. Hence total 3 vertices
- Query 2: V = 3, vertices reachable from 2 without traversing through edges with weights <= 0 are 2->1->3->4. Hence total 4 vertices
- Query 3: V = 3, vertices reachable from 3 without traversing through edges with weights <= 1 are 3->4 and 3->1. Hence total 3 vertices
Input: N = 5, M = 4, G = { {1, 2, 3}, {2, 3, 5}, {3, 4, 2}, {4, 5, 4}}, Q = 3, Q_arr = {{1, 3}, {1, 2}, {3, 1}}
Output: {1, 3, 5}
Naive Approach: To solve the problem using BFS/DFS follow the below idea:
For each query, we have to in short find the size of the connected component in which the vertex ai lie in. The connected component defined will be the set of vertices reachable from ai such that the weights are strictly greater than zi.
Follow the steps to solve the problem:
Below is the implementation for the above approach:
3 4 3
Time Complexity: O(Q*(N+M))
Auxiliary Space: O(M)
Efficient Approach: To solve the problem using Disjoint Set follow the below idea:
For each qth query, maintain a union find set with each individual set having vertices whose weights are strictly greater than zi. Sort the queries and graph in the decreasing order of weights since union-find can only merge the two connected components but not disconnect them. Hence with each query sorted in decreasing order the union operation needs to be performed with the previously solved query since the weights will decrease and not increase.
Follow the steps to solve the problem:
UnionFind class to represent a disjoint set data structure.UnionFind class to initialize the parent and size arrays.findParent method in the UnionFind class to find the representative (root) of a set.mergeSets method in the UnionFind class to merge two sets.getSize method in the UnionFind class to get the size of a set.Edge struct to represent an edge in the graph.Query struct to represent a query.main function, declare, and initialize the necessary variables such as the number of vertices, edges, and queries.UnionFind class with the given number of vertices.3 4 3
Time Complexity: O(Z + ZlogZ), where Z = (Q+M).
Auxiliary Space: O(Z)