- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 82 lines of C++ from the credited upstream file 2709.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 7 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), sz(n, 1) {4 iota(id.begin(), id.end(), 0);5 }6 7 void unionBySize(int u, int v) {8 const int i = find(u);9 const int j = find(v);10 if (i == j)11 return;12 if (sz[i] < sz[j]) {13 sz[j] += sz[i];14 id[i] = j;15 } else {16 sz[i] += sz[j];17 id[j] = i;18 }19 }20 21 int getSize(int i) {22 return sz[i];23 }24 25 private:26 vector<int> id;27 vector<int> sz;28 29 int find(int u) {30 return id[u] == u ? u : id[u] = find(id[u]);31 }32};33 34class Solution {35 public:36 bool canTraverseAllPairs(vector<int>& nums) {37 const int n = nums.size();38 const int mx = ranges::max(nums);39 const vector<int> minPrimeFactors = sieveEratosthenes(mx + 1);40 unordered_map<int, int> primeToFirstIndex;41 UnionFind uf(n);42 43 for (int i = 0; i < n; ++i)44 for (const int primeFactor : getPrimeFactors(nums[i], minPrimeFactors))45 46 if (const auto it = primeToFirstIndex.find(primeFactor);47 it != primeToFirstIndex.cend())48 uf.unionBySize(it->second, i);49 else50 primeToFirstIndex[primeFactor] = i;51 52 for (int i = 0; i < n; ++i)53 if (uf.getSize(i) == n)54 return true;55 56 return false;57 }58 59 private:60 61 vector<int> sieveEratosthenes(int n) {62 vector<int> minPrimeFactors(n + 1);63 iota(minPrimeFactors.begin() + 2, minPrimeFactors.end(), 2);64 for (int i = 2; i * i < n; ++i)65 if (minPrimeFactors[i] == i) 66 for (int j = i * i; j < n; j += i)67 minPrimeFactors[j] = min(minPrimeFactors[j], i);68 return minPrimeFactors;69 }70 71 vector<int> getPrimeFactors(int num, const vector<int>& minPrimeFactors) {72 vector<int> primeFactors;73 while (num > 1) {74 const int divisor = minPrimeFactors[num];75 primeFactors.push_back(divisor);76 while (num % divisor == 0)77 num /= divisor;78 }79 return primeFactors;80 }81};82