- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 84 lines of C++ from the credited upstream file maximum-points-activated-with-one-addition.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 6 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.
123 45class Solution {6public:7 int maxActivated(vector<vector<int>>& points) {8 static const int N_DIM = 2;9 static const int N_ADD = 1;10 11 UnionFind uf(size(points));12 vector<unordered_map<int, int>> lookup(N_DIM);13 for (int i = 0; i < size(points); ++i) {14 for (int j = 0; j < size(lookup); ++j) {15 if (lookup[j].count(points[i][j])) {16 uf.union_set(i, lookup[j][points[i][j]]);17 } else {18 lookup[j][points[i][j]] = i;19 }20 }21 }22 vector<int> top(min(N_ADD + 1, static_cast<int>(size(points))));23 for (int i = 0; i < size(points); ++i) {24 if (uf.find_set(i) != i) {25 continue;26 }27 for (int j = 0, s = uf.total(i); j < size(top); ++j) {28 if (s > top[j]) {29 swap(top[j], s);30 }31 }32 }33 return accumulate(cbegin(top), cend(top), 0) + N_ADD;34 }35 36private:37 class UnionFind {38 public:39 UnionFind(int n)40 : set_(n)41 , rank_(n)42 , size_(n, 1) {43 iota(set_.begin(), set_.end(), 0);44 }45 46 int find_set(int x) {47 vector<int> stk;48 while (set_[x] != x) { 49 stk.emplace_back(x);50 x = set_[x];51 }52 while (!empty(stk)) {53 const int y = stk.back(); stk.pop_back();54 set_[y] = x;55 }56 return x;57 }58 59 bool union_set(int x, int y) {60 x = find_set(x), y = find_set(y);61 if (x == y) {62 return false;63 }64 if (rank_[x] > rank_[y]) {65 swap(x, y);66 } else if (rank_[x] == rank_[y]) {67 ++rank_[y];68 }69 set_[x] = y; 70 size_[y] += size_[x];71 return true;72 }73 74 int64_t total(int x) {75 return size_[find_set(x)];76 }77 78 private:79 vector<int> set_;80 vector<int> rank_;81 vector<int64_t> size_;82 };83};84