- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 52 lines of C++ from the credited upstream file 1627.cpp.
- The implementation visibly relies on sequence storage.
- 3 loop blocks detected.
Complexity
Account for every find and union operation; with path compression and ranked merging, the amortized cost is nearly constant per operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class UnionFind {2 public:3 UnionFind(int n) : id(n), rank(n) {4 iota(id.begin(), id.end(), 0);5 }6 7 bool unionByRank(int u, int v) {8 const int i = find(u);9 const int j = find(v);10 if (i == j)11 return false;12 if (rank[i] < rank[j]) {13 id[i] = j;14 } else if (rank[i] > rank[j]) {15 id[j] = i;16 } else {17 id[i] = j;18 ++rank[j];19 }20 return true;21 }22 23 int find(int u) {24 return id[u] == u ? u : id[u] = find(id[u]);25 }26 27 private:28 vector<int> id;29 vector<int> rank;30};31 32class Solution {33 public:34 vector<bool> areConnected(int n, int threshold,35 vector<vector<int>>& queries) {36 vector<bool> ans;37 UnionFind uf(n + 1);38 39 for (int z = threshold + 1; z <= n; ++z)40 for (int x = z * 2; x <= n; x += z)41 uf.unionByRank(z, x);42 43 for (const vector<int>& query : queries) {44 const int a = query[0];45 const int b = query[1];46 ans.push_back(uf.find(a) == uf.find(b));47 }48 49 return ans;50 }51};52