简体   繁体   English

用于实现不交集(联合查找)的数据结构是什么?

[英]What data structure to use for the implementation of disjoint sets(union find)?

Please note that this is not a homework question. 请注意,这不是作业问题。 I am training on Kattis and I came by a question that requires the use of Union-Find paradigms. 我正在接受有关Kattis的培训,并且遇到一个问题,需要使用Union-Find范例。 Given the nature of the problem, I decided to implement my own UnionFind data structure. 考虑到问题的性质,我决定实现自己的UnionFind数据结构。 I understand that the interface of my DS should support: 我了解我的DS界面应支持:

  1. makeSet makeSet
  2. find(elem) -> returns reference to the representative of that set find(elem)->返回对该集合的代表的引用
  3. merge(firstElem, secondElem) -> merges the two parents of that set(also makes sure it is balanced) merge(firstElem,secondElem)->合并该集合的两个父代(还要确保它是平衡的)

Now the issue is I am not implementing this data structure to support Integers which is usually implemented using an array where the index is the value and the representative of the set is always the value at that index. 现在的问题是,我没有实现此数据结构来支持Integers,通常使用索引为值而集合的代表始终为该索引处的值的数组来实现Integers。 Instead my set contains strings and I am finding difficulty in choosing the data structure. 相反,我的集合包含字符串,并且在选择数据结构时遇到了困难。

if you have data like String [] universal_set = {"a,b,s","d,s,w","s,d,v","m,d,s"}; 如果您有String [] universal_set = {"a,b,s","d,s,w","s,d,v","m,d,s"}; , create a HashMap and get unique values then group them as a disjoint sub set of the main set. ,创建一个HashMap并获取唯一值,然后将它们分组为主要集合的不相交子集。

Here is a soultion for String-String union find, which may help. 这是String-String联合查找的提示,可能有所帮助。

//set all pairs
for(String[] pair : pairs){
            String parent0 = find(pair[0], map);
            String parent1 = find(pair[1], map);
            if(!parent0.equals(parent1)) map.put(parent0, parent1);
        }
//check if two string are same group
find(words1[i], map).equals(find(words2[i], map)

//find 
private String find(String word, Map<String, String> map){
        if(!map.containsKey(word)) return word;
        String str = word;
        while(map.containsKey(str)){
            str = map.get(str);
        }
        map.put(word, str);
        return str;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM