# 并查集（union-find）

leetcode-1202. Smallest String With Swaps

class Solution {
public:
int _find(unordered_map<int, pair<int, int>>& parents, int node)
{
while (parents.at(node).first != node)
{
node = parents.at(node).first;
}
return node;
}

void _union(unordered_map<int, pair<int, int>>& parents, int nodeA, int nodeB)
{
int parentA = _find(parents, nodeA);
int parentB = _find(parents, nodeB);
if (parentA == parentB)
{
return ;
}
if (parents.at(parentA).second >= parents.at(parentB).second)
{
parents.at(parentB).first = parentA;
parents.at(parentA).second += parents.at(parentB).second;
}
else
{
parents.at(parentA).first = parentB;
parents.at(parentB).second += parents.at(parentA).second;
}
}

string smallestStringWithSwaps(string s, vector<vector<int>>& pairs) {
if (pairs.empty())
{
return s;
}
unordered_map<int, pair<int, int>> parents;
for (int i = 0; i < s.size(); ++i)
{
parents[i] = {i, 1};
}
for (auto& _pair : pairs)
{
_union(parents, _pair.at(0), _pair.at(1));
}

unordered_map<int, vector<char>> summary;
for (auto& info : parents)
{
summary[_find(parents, info.second.first)].push_back(s.at(info.first));
}

for (auto& info : summary)
{
sort(info.second.rbegin(), info.second.rend());
}
string result ;
for (int i = 0; i < s.size(); ++i)
{
result.push_back(summary.at(_find(parents, i)).back());
summary.at(_find(parents, i)).pop_back();
}
return result;
}
};
The second element for recording the number of nodes belonging to a specific parent is necessary; otherwise, time limit may be exceeded.

## Reference

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客