並查集(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

  1. leetcode-1202. Smallest String With Swaps-C++ Solution with Find and Union
  2. 並查集(Union-Find)算法介紹
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章