File tree 1 file changed +65
-0
lines changed
most-stones-removed-with-same-row-or-column
1 file changed +65
-0
lines changed Original file line number Diff line number Diff line change
1
+ struct dsu {
2
+ vector<int > parent;
3
+ vector<int > sz;
4
+
5
+ void _init (int x){
6
+ parent.assign (x, 0 );
7
+ sz.assign (x,0 );
8
+
9
+ for (int i = 0 ; i < x; ++i){
10
+ parent[i] = i;
11
+ sz[i] = 1 ;
12
+ }
13
+ }
14
+
15
+ int find_set (int x){
16
+ if (x == parent[x])
17
+ return x;
18
+ return parent[x] = find_set (parent[x]);
19
+ }
20
+
21
+ void _union (int a, int b){
22
+ a = find_set (a);
23
+ b = find_set (b);
24
+
25
+ if (sz[a] < sz[b])
26
+ swap (a,b);
27
+
28
+ parent[b] = a;
29
+ sz[a] += sz[b];
30
+ }
31
+ };
32
+
33
+ class Solution {
34
+ public:
35
+ int removeStones (vector<vector<int >>& stones) {
36
+ int n = stones.size ();
37
+ dsu G;
38
+ G._init (n+1 );
39
+
40
+ map<int , vector<int >> rowmap, colmap;
41
+ for (int i = 0 ; i < n; ++i){
42
+ rowmap[stones[i][0 ]].push_back (i);
43
+ colmap[stones[i][1 ]].push_back (i);
44
+ }
45
+
46
+ int nodes = n;
47
+ for (int i = 0 ; i < n; ++i){
48
+ for (auto j: rowmap[stones[i][0 ]]){
49
+ if (G.find_set (i) != G.find_set (j)){
50
+ G._union (i, j);
51
+ nodes--;
52
+ }
53
+ }
54
+
55
+ for (auto j: colmap[stones[i][1 ]]){
56
+ if (G.find_set (i) != G.find_set (j)){
57
+ G._union (i, j);
58
+ nodes--;
59
+ }
60
+ }
61
+ }
62
+
63
+ return n - nodes;
64
+ }
65
+ };
You can’t perform that action at this time.
0 commit comments