Problem Description
We are given n cities labeled from 1 to n. Two cities, x and y, are directly connected by a bidirectional road if and only if they share a common divisor strictly greater than a given threshold. The goal is to determine, for a list of queries, whether two given cities are connected (directly or indirectly).
Key Insights
- Rather than connecting every pair of cities, iterate over potential common divisors (d) that are strictly greater than threshold.
- For each divisor d (in the range threshold+1 to n), all multiples of d are guaranteed to be connected.
- Use a Union Find (Disjoint Set Union) data structure to efficiently merge sets of cities that share a divisor.
- After processing connections, answer each query by checking if two cities belong to the same connected component.
Space and Time Complexity
Time Complexity: O(n log n + Q * α(n))
Space Complexity: O(n)
Solution
We use the Union Find data structure to merge connected cities. For each divisor d from threshold+1 to n, iterate through its multiples and union them. Finally, for each query, we check whether the two cities have the same root (i.e., belong to the same component).
Code Solutions
Python solution:
JavaScript solution:
C++ solution:
Java solution: