python----並查集

來源:互聯網
上載者:User

標籤:遍曆   UI   weight   通過   while   pen   utf-8   nbsp   def   

Quick Find

# -*- coding: utf-8 -*-class QuickFind(object):    id = []    cnt = 0  # the number of the sets    def __init__(self, n):        self.cnt = n        for i in range(0, n):            self.id.append(i)    def connected(self, p, q):        return self.find(p) == self.find(q)    def find(self,p):        return self.id[p]    def union(self,p,q):        id_p = self.find(p)        if not self.connected(p,q):            for i in range(0,len(self.id)):                if self.id[i] == id_p:                    self.id[i] = self.id[q]  #combine            self.cnt -= 1qf = QuickFind(10)print("initial id list is %s" % (‘,‘).join(str(x) for x in qf.id))list = [        (4,3),        (3,8),        (6,5),        (9,4),        (2,1),        (8,9),        (5,0),        (7,2),        (6,1),        (1,0),        (6,7)        ]for edge in list :    p = edge[0]    q = edge[1]    qf.union(p,q)    print("%d and %d is connected? %s"%(p,q,str(qf.connected(p,q))))print("final id list is %s" %(",").join(str(x) for x in qf.id))print("count of sets is : %d" % qf.cnt)

 connect更新的時候需要遍曆,可以借用樹結構來減小時間複雜度。

# -*- coding: utf-8 -*-class QuickUnion(object):    id = []    cnt = 0  # the number of the sets    def __init__(self, n):        self.cnt = n        for i in range(0, n):            self.id.append(i)    def connected(self, p, q):        return self.find(p) == self.find(q)    def find(self,x):        while(x != self.id[x]):            x = self.id[x]        return x    def union(self,p,q):        root_p = self.find(p)        root_q = self.find(q)        if not self.connected(p,q):            self.id[root_p] = root_q            self.cnt -= 1    qu = QuickUnion(10)print("initial id list is %s" % (‘,‘).join(str(x) for x in qf.id))list = [        (4,3),        (3,8),        (6,5),        (9,4),        (2,1),        (8,9),        (5,0),        (7,2),        (6,1),        (1,0),        (6,7)        ]for edge in list :    p = edge[0]    q = edge[1]    qu.union(p,q)    print("%d and %d is connected? %s"%(p,q,str(qu.connected(p,q))))print("final id list is %s" %(",").join(str(x) for x in qu.id))print("count of sets is : %d" % qu.cnt)

 

 

 

 Weighted Quick Union

 Quick Union 可能會退化成鏈,導致效能下降,可以通過Weighted Quick Union盡量平衡樹的高度,從而提升效能。

# -*- coding: utf-8 -*-class WeightedQuickUnion(object):    id = []    cnt = 0  # the number of the sets    sz = []    def __init__(self, n):        self.cnt = n        for i in range(0, n):            self.id.append(i)            self.sz.append(1)    def connected(self, p, q):        return self.find(p) == self.find(q)    def find(self,x):        while(x != self.id[x]):            x = self.id[x]        return x    def union(self,p,q):        root_p = self.find(p)        root_q = self.find(q)        if not self.connected(p,q):            if self.sz[q] > self.sz[p]:    #保證小樹連大樹,若大樹連小樹可能退化成鏈                self.id[root_p] = root_q                self.cnt -= 1                self.sz[q] += self.sz[p]            else :                self.id[root_q] = root_p                self.cnt -= 1                self.sz[p] += self.sz[q]wqu = WeightedQuickUnion(10)print("initial id list is %s" % (‘,‘).join(str(x) for x in wqu.id))list = [        (4,3),        (3,8),        (6,5),        (9,4),        (2,1),        (8,9),        (5,0),        (7,2),        (6,1),        (1,0),        (6,7)        ]for edge in list :    p = edge[0]    q = edge[1]    wqu.union(p,q)    print("%d and %d is connected? %s"%(p,q,str(wqu.connected(p,q))))print("final id list is %s" %(",").join(str(x) for x in wqu.id))print("count of components is : %d" % wqu.cnt)

可通過壓縮尋找進一步提升效能,類似樹樁。

 

參考:http://www.cnblogs.com/learnbydoing/p/6896472.html?utm_source=itdadao&utm_medium=referral

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.