簡體   English   中英

用於實現不交集(聯合查找)的數據結構是什么?

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

請注意,這不是作業問題。 我正在接受有關Kattis的培訓,並且遇到一個問題,需要使用Union-Find范例。 考慮到問題的性質,我決定實現自己的UnionFind數據結構。 我了解我的DS界面應支持:

  1. makeSet
  2. find(elem)->返回對該集合的代表的引用
  3. merge(firstElem,secondElem)->合並該集合的兩個父代(還要確保它是平衡的)

現在的問題是,我沒有實現此數據結構來支持Integers,通常使用索引為值而集合的代表始終為該索引處的值的數組來實現Integers。 相反,我的集合包含字符串,並且在選擇數據結構時遇到了困難。

如果您有String [] universal_set = {"a,b,s","d,s,w","s,d,v","m,d,s"}; ,創建一個HashMap並獲取唯一值,然后將它們分組為主要集合的不相交子集。

這是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