1. 题目来源
2. 题目解析
并查集维护连通块即可,在考场上并没有考虑的很完备,猜了猜思路就写了。当为树形连通的时候,得从入度为 1 的点进行考虑,然后见该点删除,考虑下一个入度为 1 的点。
- 时间复杂度: O ( n ) O(n) O(n)。
- 空间复杂度: O ( n ) O(n) O(n)
代码:
class Solution {
public:
vector<int> p;
int find(int x) {
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}
int minimumHammingDistance(vector<int>& a, vector<int>& b, vector<vector<int>>& as) {
int n = a.size();
for (int i = 0; i < n; i ++ ) p.push_back(i);
for (auto &t : as) p[find(t[0])] = find(t[1]);
vector<unordered_multiset<int>> hash(n);
for (int i = 0; i < n; i ++ )
hash[find(i)].insert(a[i]);
int res = 0;
for (int i = 0; i < n; i ++ ) {
auto &h = hash[find(i)]; // 寻找b[i]这个点所在连通块的集合
if (h.count(b[i])) h.erase(h.find(b[i]));
else res ++ ;
}
return res;
}
};