-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminimizeHammingDistanceAfterSwapOperations.cpp
More file actions
58 lines (52 loc) · 1.37 KB
/
minimizeHammingDistanceAfterSwapOperations.cpp
File metadata and controls
58 lines (52 loc) · 1.37 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
// Source: https://leetcode.com/problems/minimize-hamming-distance-after-swap-operations/
// Author: Miao Zhang
// Date: 2021-06-01
class UnionFind {
public:
UnionFind(int n): p_(n) {
iota(begin(p_), end(p_), 0);
};
int find(int x) {
if (p_[x] != x) {
p_[x] = find(p_[x]);
}
return p_[x];
}
void merge(int x, int y) {
int px = find(x);
int py = find(y);
if (px != py) {
p_[px] = py;
}
}
private:
vector<int> p_;
};
class Solution {
public:
int minimumHammingDistance(vector<int>& source, vector<int>& target, vector<vector<int>>& allowedSwaps) {
int n = source.size();
UnionFind uf(n);
for (auto a: allowedSwaps) {
uf.merge(uf.find(a[0]), uf.find(a[1]));
}
unordered_map<int, unordered_multiset<int>> s, t;
for (int i = 0; i < n; i++) {
int pi = uf.find(i);
s[pi].insert(source[i]);
t[pi].insert(target[i]);
}
int res = 0;
for (int i = 0; i < n; i++) {
if (s.find(i) == s.end()) continue;
for (int x: s[i]) {
if (t[i].find(x) == t[i].end()) {
res++;
} else {
t[i].erase(t[i].find(x));
}
}
}
return res;
}
};