Problem Description
You are given an undirected graph with n nodes and an edge list where each edge is specified by two endpoints and a distance. The task is to answer multiple queries, each asking whether there exists a path between two given nodes such that every edge on that path has a weight strictly less than a given limit. Note that the graph may be disconnected and there can be multiple edges between two nodes.
Key Insights
- Offline processing: Sort queries by their limit value and process edges in increasing order.
- Union-Find Data Structure: Use it to dynamically merge components as you process allowed edges.
- Edge Filtering: Only add an edge if its distance is strictly less than the current query’s limit, ensuring no invalid edge is included.
- Efficiency: Sorting edges and queries allows efficient union operations and quick connectivity checks.
Space and Time Complexity
Time Complexity: O((E + Q) log(E + Q)) where E is the number of edges and Q is the number of queries, due to sorting and near constant-time union-find operations. Space Complexity: O(n + E + Q) for storing union-find structure, edges, and queries.
Solution
The approach takes advantage of offline query processing and the union-find (disjoint set union) data structure. First, sort all edges based on their distances. Then, sort the queries based on their limit values. Iterate through the sorted queries and for each query add all the edges from the sorted edge list that have a distance strictly less than the query’s limit. After adding these edges by performing union operations, check if the two nodes from the query belong to the same component using the union-find structure. If they do, the answer is true; otherwise, false.