1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| class DisjointSetUnion { private: unordered_map<int, int> f, rank; public: int find(int x) { if (f.find(x) == f.end()) { f[x] = x; rank[x] = 1; } return f[x] == x ? x : f[x] = find(f[x]); } void unionSet(int x, int y) { int fx = find(x), fy = find(y); if (fx != fy) { if (rank[fx] > rank[fy]) swap(fx, fy); rank[fy] += rank[fx]; f[fx] = fy; } } int numberOfConnectedComponent() { int cnt = 0; for (auto &[x, fa] : f) if (x == fa) ++cnt; return cnt; } }; class Solution { public: int removeStones(vector<vector<int>> &stones) { const int n = stones.size(); DisjointSetUnion dsu; for (int i = 0; i < n; ++i) dsu.unionSet(stones[i][0], stones[i][1] + 10000); return n - dsu.numberOfConnectedComponent(); } };
|