-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetcode1722.cpp
More file actions
67 lines (52 loc) · 1.43 KB
/
Leetcode1722.cpp
File metadata and controls
67 lines (52 loc) · 1.43 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
class Solution {
public:
vector<int> parent, rankv;
int find(int x) {
if (parent[x] == x) return x;
return parent[x] = find(parent[x]);
}
void unite(int a, int b) {
int pa = find(a);
int pb = find(b);
if (pa == pb) return;
if (rankv[pa] < rankv[pb]) {
parent[pa] = pb;
} else if (rankv[pa] > rankv[pb]) {
parent[pb] = pa;
} else {
parent[pb] = pa;
rankv[pa]++;
}
}
int minimumHammingDistance(vector<int>& source, vector<int>& target, vector<vector<int>>& allowedSwaps) {
int n = source.size();
parent.resize(n);
rankv.assign(n, 0);
for (int i = 0; i < n; i++) {
parent[i] = i;
}
for (auto &p : allowedSwaps) {
unite(p[0], p[1]);
}
unordered_map<int, vector<int>> groups;
for (int i = 0; i < n; i++) {
groups[find(i)].push_back(i);
}
int ans = 0;
for (auto &it : groups) {
unordered_map<int, int> freq;
for (int idx : it.second) {
freq[source[idx]]++;
}
for (int idx : it.second) {
freq[target[idx]]--;
}
for (auto &x : freq) {
if (x.second > 0) {
ans += x.second;
}
}
}
return ans;
}
};