给你两个整数数组 source 和 target ,长度都是 n 。还有一个数组 allowedSwaps ,其中每个 allowedSwaps[i] = [ai, bi] 表示你可以交换数组 source 中下标为 ai 和 bi(下标从 0 开始 )的两个元素。注意,你可以按 任意 顺序 多次 交换一对特定下标指向的元素。
相同长度的两个数组 source 和 target 间的 汉明距离 是元素不同的下标数量。形式上,其值等于满足 source[i] != target[i] (下标从 0 开始 )的下标 i(0 <= i <= n-1)的数量。
在对数组 source 执行 任意 数量的交换操作后,返回 source 和 target 间的 最小汉明距离 。
示例 1:
输入:source = [1,2,3,4], target = [2,1,4,5], allowedSwaps = [[0,1],[2,3]]
输出:1
解释:source 可以按下述方式转换:
- 交换下标 0 和 1 指向的元素:source = [2,1,3,4]
- 交换下标 2 和 3 指向的元素:source = [2,1,4,3]
source 和 target 间的汉明距离是 1 ,二者有 1 处元素不同,在下标 3 。
示例 2:
输入:source = [1,2,3,4], target = [1,3,2,4], allowedSwaps = []
输出:2
解释:不能对 source 执行交换操作。
source 和 target 间的汉明距离是 2 ,二者有 2 处元素不同,在下标 1 和下标 2 。
示例 3:
输入:source = [5,1,2,4,3], target = [1,5,4,2,3], allowedSwaps = [[0,4],[4,2],[1,3],[1,4]]
输出:0
提示:
n == source.length == target.length1 <= n <= 10^51 <= source[i], target[i] <= 10^50 <= allowedSwaps.length <= 10^5allowedSwaps[i].length == 20 <= ai, bi <= n - 1ai != bi
分析:先用并查集将可交换的位置分成多个集合,之后根据划分的集合,分别用若干个数组,记录 source 和 target 中对应位置的元素。接着对比这些数组中不同元素的数量即可。
cpp
class Solution {
public:
int findFather(int a,int father[])
{
int pos=a;
while(pos!=father[pos])pos=father[pos];
while(a!=pos)
{
int temp=father[a];
father[a]=pos,a=temp;
}
return pos;
}
void merge(int a,int b,int father[])
{
int fa=findFather(a,father),fb=findFather(b,father);
if(fa!=fb)
{
if(fa<fb)father[fb]=fa;
else father[fa]=fb;
}
return;
}
int minimumHammingDistance(vector<int>& source, vector<int>& target, vector<vector<int>>& allowedSwaps) {
int n=source.size(),m=allowedSwaps.size(),ans=0;
int father[n+5];
for(int i=0;i<n;++i)father[i]=i;
for(int i=0;i<m;++i)
merge(allowedSwaps[i][0],allowedSwaps[i][1],father);
for(int i=0;i<n;++i)findFather(i,father);
vector<vector<int>>vec_s(n),vec_t(n);
for(int i=0;i<n;++i)
{
vec_s[father[i]].push_back(source[i]);
vec_t[father[i]].push_back(target[i]);
}
int len=vec_s.size();
for(int i=0;i<len;++i)
{
if(vec_s[i].size()==0)continue;
sort(vec_s[i].begin(),vec_s[i].end());
sort(vec_t[i].begin(),vec_t[i].end());
int pos_s=0,pos_t=0,l1=vec_s[i].size(),l2=vec_t[i].size();
while(pos_s<l1&&pos_t<l2)
{
if(vec_s[i][pos_s]==vec_t[i][pos_t])pos_s++,pos_t++,ans++;
else if(vec_s[i][pos_s]<vec_t[i][pos_t])pos_s++;
else pos_t++;
}
}
return n-ans;
}
};