leetcodeSolution to some Leetcode problems written in C++ |
git clone git://git.dimitrijedobrota.com/leetcode.git |
Log | Files | Refs | README | LICENSE |
1722.cpp (1240B)
0 class UnionFind {
1 int n, cnt = n;
2 vector<int> root, size;
4 public:
5 UnionFind(int n) : n(n), root(n), size(n, 1) { iota(root.begin(), root.end(), 0); }
7 int find(int x) {
8 while (x != root[x])
9 x = root[x] = root[root[x]];
10 return x;
11 }
13 void join(int x, int y) {
14 x = find(x), y = find(y);
15 if (x != y) {
16 if (size[x] > size[y]) swap(x, y);
17 root[x] = y;
18 size[y] += size[x];
19 cnt--;
20 }
21 }
23 int count() { return cnt; }
24 bool connected(int x, int y) { return find(x) == find(y); }
25 };
27 class Solution {
28 public:
29 int minimumHammingDistance(vector<int> &source, vector<int> &target, vector<vector<int>> &allowedSwaps) {
30 int n = source.size();
31 UnionFind uf(n);
33 for (auto &s : allowedSwaps)
34 uf.join(s[0], s[1]);
36 vector<unordered_map<int, int>> vus(n);
37 for (int i = 0; i < n; i++) {
38 int pos = uf.find(i);
39 vus[pos][target[i]]++;
40 vus[pos][source[i]]--;
41 }
43 int res = 0;
44 for (int i = 0; i < n; i++)
45 for (auto [_, val] : vus[i])
46 res += abs(val);
48 return res / 2;
49 }
50 };