-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcouples_holding_hands.cpp
More file actions
85 lines (73 loc) · 1.53 KB
/
couples_holding_hands.cpp
File metadata and controls
85 lines (73 loc) · 1.53 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// 765. Couples Holding Hands: https://leetcode.com/problems/couples-holding-hands
// Author: xianfeng.zhu@gmail.com
#include <stdio.h>
#include <vector>
using std::vector;
class UnionFind
{
public:
UnionFind(int count): count_(count), couples_(count)
{
for (int i = 0; i < count; i++)
{
couples_[i] = i;
}
}
virtual ~UnionFind() = default;
int find(int idx) const
{
while (couples_[idx] != idx)
{
idx = couples_[idx];
}
return idx;
}
void connect(int a, int b)
{
a = find(a);
b = find(b);
if (a != b)
{
couples_[a] = b;
count_--;
}
}
bool isConnected(int a, int b) const
{
return find(a) == find(b);
}
int getCount() const
{
return count_;
}
private:
vector<int> couples_;
int count_;
};
class Solution
{
public:
int minSwapsCouples(const vector<int>& row)
{
int count = row.size() / 2;
UnionFind uf(count);
for (int i = 0; i < row.size(); i += 2)
{
uf.connect(row[i] / 2, row[i + 1] / 2);
}
return count - uf.getCount();
}
};
int main(int argc, char* argv[])
{
vector<int> row = {0, 2, 1, 3};
int swaps = Solution().minSwapsCouples(row);
printf("Input: row = [");
for (int i = 0; i < row.size(); i++)
{
printf("%s%d", (i != 0 ? ", " : ""), row[i]);
}
printf("]\n");
printf("Output: %d\n", swaps);
return 0;
}