1722.cpp (1240B)
1 class UnionFind { 2 int n, cnt = n; 3 vector<int> root, size; 4 5 public: 6 UnionFind(int n) : n(n), root(n), size(n, 1) { iota(root.begin(), root.end(), 0); } 7 8 int find(int x) { 9 while (x != root[x]) 10 x = root[x] = root[root[x]]; 11 return x; 12 } 13 14 void join(int x, int y) { 15 x = find(x), y = find(y); 16 if (x != y) { 17 if (size[x] > size[y]) swap(x, y); 18 root[x] = y; 19 size[y] += size[x]; 20 cnt--; 21 } 22 } 23 24 int count() { return cnt; } 25 bool connected(int x, int y) { return find(x) == find(y); } 26 }; 27 28 class Solution { 29 public: 30 int minimumHammingDistance(vector<int> &source, vector<int> &target, vector<vector<int>> &allowedSwaps) { 31 int n = source.size(); 32 UnionFind uf(n); 33 34 for (auto &s : allowedSwaps) 35 uf.join(s[0], s[1]); 36 37 vector<unordered_map<int, int>> vus(n); 38 for (int i = 0; i < n; i++) { 39 int pos = uf.find(i); 40 vus[pos][target[i]]++; 41 vus[pos][source[i]]--; 42 } 43 44 int res = 0; 45 for (int i = 0; i < n; i++) 46 for (auto [_, val] : vus[i]) 47 res += abs(val); 48 49 return res / 2; 50 } 51 };