python實現並查表

來源:互聯網
上載者:User

標籤:最佳化   return   大小   使用   尋找   pre   python   name   dict   

class UnionFindSet(object):    """並查表"""    def __init__(self, data_list):        """初始化兩個字典,一個儲存節點的父節點,另外一個儲存父節點的大小        初始化的時候,將節點的父節點設為自身,size設為1"""        self.father_dict = {}        self.size_dict = {}        for node in data_list:            self.father_dict[node] = node            self.size_dict[node] = 1    def find_head(self, node):        """使用遞迴的方式來尋找父節點        在尋找父節點的時候,順便把當前節點移動到父節點上面        這個操作算是一個最佳化        """        father = self.father_dict[node]        if(node != father):            father = self.find_head(father)        self.father_dict[node] = father        return father    def is_same_set(self, node_a, node_b):        """查看兩個節點是不是在一個集合裡面"""        return self.find_head(node_a) == self.find_head(node_b)    def union(self, node_a, node_b):        """將兩個集合合并在一起"""        if node_a is None or node_b is None:            return        a_head = self.find_head(node_a)        b_head = self.find_head(node_b)        if(a_head != b_head):            a_set_size = self.size_dict[a_head]            b_set_size = self.size_dict[b_head]            if(a_set_size >= b_set_size):                self.father_dict[b_head] = a_head                self.size_dict[a_head] = a_set_size + b_set_size            else:                self.father_dict[a_head] = b_head                self.size_dict[b_head] = a_set_size + b_set_sizeif __name__ == ‘__main__‘:    a = [1,2,3,4,5]    union_find_set = UnionFindSet(a)    union_find_set.union(1,2)    union_find_set.union(3,5)    union_find_set.union(3,1)    print(union_find_set.is_same_set(2,5))  # True

 

python實現並查表

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.