简体   繁体   中英

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. Given the nature of the problem, I decided to implement my own UnionFind data structure. I understand that the interface of my DS should support:

  1. makeSet
  2. find(elem) -> returns reference to the representative of that set
  3. merge(firstElem, secondElem) -> merges the two parents of that set(also makes sure it is balanced)

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. 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"}; , create a HashMap and get unique values then group them as a disjoint sub set of the main set.

Here is a soultion for String-String union find, which may help.

//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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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