并查集(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)算法介绍
发布了11 篇原创文章 · 获赞 5 · 访问量 2696
展开阅读全文

没有更多推荐了,返回首页

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

分享到微信朋友圈

×

扫一扫,手机浏览