Skip to content

Commit f7f02d4

Browse files
authored
Update 1722.Minimize-Hamming-Distance-After-Swap-Operations.cpp
1 parent aeb9822 commit f7f02d4

File tree

1 file changed

+34
-38
lines changed

1 file changed

+34
-38
lines changed
Lines changed: 34 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,57 +1,53 @@
11
class Solution {
22
vector<int>Father;
3+
int FindFather(int x)
4+
{
5+
if (Father[x]!=x)
6+
Father[x] = FindFather(Father[x]);
7+
return Father[x];
8+
}
9+
10+
void Union(int x, int y)
11+
{
12+
x = Father[x];
13+
y = Father[y];
14+
if (x<y) Father[y] = x;
15+
else Father[x] = y;
16+
}
17+
318
public:
4-
string smallestStringWithSwaps(string s, vector<vector<int>>& pairs) {
5-
int N = s.size();
6-
Father.resize(N);
7-
for (int i=0; i<N; i++)
19+
int minimumHammingDistance(vector<int>& source, vector<int>& target, vector<vector<int>>& allowedSwaps)
20+
{
21+
int n = source.size();
22+
Father.resize(n);
23+
for (int i=0; i<n; i++)
824
Father[i] = i;
925

10-
for (auto& p :pairs)
26+
for (auto pair: allowedSwaps)
1127
{
12-
int a = p[0];
13-
int b = p[1];
28+
int a = pair[0];
29+
int b = pair[1];
1430
if (FindFather(a)!=FindFather(b))
1531
Union(a,b);
1632
}
1733

18-
unordered_map<int, vector<int>>Map; // root idx -> all indexes
19-
for (int i=0; i<N; i++)
20-
{
34+
unordered_map<int,vector<int>>Map;
35+
for (int i=0; i<n; i++)
2136
Map[FindFather(i)].push_back(i);
22-
}
2337

38+
int count = 0;
2439
for (auto x: Map)
2540
{
26-
string temp;
27-
for (auto idx : x.second)
28-
temp.push_back(s[idx]);
29-
sort(temp.begin(),temp.end());
30-
int k = 0;
31-
for (auto idx : x.second)
41+
multiset<int>Set;
42+
for (auto i: x.second)
43+
Set.insert(source[i]);
44+
for (auto i: x.second)
3245
{
33-
s[idx] = temp[k];
34-
k++;
46+
if (Set.find(target[i])!=Set.end())
47+
Set.erase(Set.lower_bound(target[i]));
3548
}
49+
count += Set.size();
3650
}
37-
38-
return s;
39-
}
40-
41-
int FindFather(int x)
42-
{
43-
if (Father[x]!=x)
44-
Father[x] = FindFather(Father[x]);
45-
return Father[x];
46-
}
47-
48-
void Union(int x, int y)
49-
{
50-
x = Father[x];
51-
y = Father[y];
52-
if (x<y)
53-
Father[y] = x;
54-
else
55-
Father[x] = y;
51+
return count;
5652
}
5753
};

0 commit comments

Comments
 (0)