- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 59 lines of C++ from the credited upstream file 1724.cpp.
- The implementation visibly relies on sequence storage, ordered lookup.
- 2 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() {}4 UnionFind(int n) {5 id.resize(n);6 7 for (int i = 0; i < n; ++i)8 id[i][0] = i;9 }10 11 void union_(int u, int v, int limit) {12 const int i = find(u, limit);13 const int j = find(v, limit);14 if (i == j)15 return;16 id[i][limit] = j;17 }18 19 int find(int u, int limit) {20 21 const auto it = id[u].upper_bound(limit);22 const int i = prev(it)->second;23 if (i == u)24 return u;25 26 const int j = find(i, limit);27 id[u][limit] = j;28 return j;29 }30 31 private:32 33 vector<map<int, int>> id;34};35 36class DistanceLimitedPathsExist {37 public:38 DistanceLimitedPathsExist(int n, vector<vector<int>>& edgeList) {39 uf = UnionFind(n);40 41 ranges::sort(edgeList, ranges::less{},42 [](const vector<int>& edge) { return edge[2]; });43 44 for (const vector<int>& edge : edgeList) {45 const int u = edge[0];46 const int v = edge[1];47 const int d = edge[2];48 uf.union_(u, v, d);49 }50 }51 52 bool query(int p, int q, int limit) {53 return uf.find(p, limit - 1) == uf.find(q, limit - 1);54 }55 56 private:57 UnionFind uf;58};59