-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path1722.cpp
More file actions
60 lines (60 loc) · 1.62 KB
/
1722.cpp
File metadata and controls
60 lines (60 loc) · 1.62 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
class DisjointSet {
private:
vector<int> parents;
vector<int> ranks;
public:
DisjointSet(int n) {
parents.resize(n, 0);
for (int i = 0; i < n; ++i) parents[i] = i;
ranks.resize(n, 1);
}
int find(int x) {
if (parents[x] != x) {
parents[x] = find(parents[x]);
}
return parents[x];
}
void join(int x, int y) {
int pX = find(x);
int pY = find(y);
if (pX == pY) return;
if (ranks[pX] > ranks[pY]) {
parents[pY] = pX;
}
else if (ranks[pX] < ranks[pY]) {
parents[pX] = pY;
}
else {
parents[pY] = pX;
ranks[pX]++;
}
}
};
class Solution {
public:
int minimumHammingDistance(vector<int>& source, vector<int>& target, vector<vector<int>>& allowedSwaps) {
int n = source.size();
DisjointSet* disjointSet = new DisjointSet(n);
for (auto& allowedSwap : allowedSwaps) {
disjointSet->join(allowedSwap[0], allowedSwap[1]);
}
unordered_map<int, vector<int>> idx2group;
for (int i = 0; i < n; ++i) {
int idx = disjointSet->find(i);
idx2group[idx].push_back(i);
}
int res = 0;
unordered_map<int, int> num2cnt;
for (auto& [idx, group] : idx2group) {
num2cnt.clear();
for (auto& ind : group) {
num2cnt[source[ind]]++;
num2cnt[target[ind]]--;
}
for (auto& [num, cnt] : num2cnt) {
if (cnt > 0) res += cnt;
}
}
return res;
}
};