-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremoveStones.cpp
More file actions
69 lines (68 loc) · 1.74 KB
/
removeStones.cpp
File metadata and controls
69 lines (68 loc) · 1.74 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
class Solution {
public:
class UnionFind {
public:
UnionFind(int n): size(n), p(n), rank(n, 1) {
iota(p.begin(), p.end(), 0);
}
int find(int e) {
int t = e;
while (p[t] != t) {
t = p[t];
}
while (p[e] != t) {
int temp = p[e];
p[e] = t;
e = temp;
}
return t;
}
bool connect(int x, int y) {
x = find(x);
y = find(y);
if (x == y) {
return false;
}
if (rank[x] < rank[y]) {
swap(x, y);
}
p[y] = x;
rank[x] += rank[y];
return true;
}
int groups() {
int ans = 0;
for (int i = 0; i < size; ++i) {
if (p[i] == i)
++ans;
}
return ans;
}
private:
vector<int> p, rank;
int size;
};
int removeStones(vector<vector<int>>& stones) {
unordered_map<int, vector<int>> m1, m2;
int n = stones.size();
if (n == 1) return 0;
for (int i = 0; i < n; ++i) {
auto &v = stones[i];
m1[v[0]].push_back(i);
m2[v[1]].push_back(i);
}
UnionFind uf(n);
auto f = [&](unordered_map<int, vector<int>> &m) {
for (auto &[k, v]: m) {
for (int i = 0; i < v.size() - 1; ++i) {
for (int j = i + 1; j < v.size(); ++j) {
uf.connect(v[i], v[j]);
}
}
}
};
f(m1);
f(m2);
return n - uf.groups();
}
};