본문 바로가기

00/algorithm

Union Find

반응형

 

  • Find(x): get the identity of the group that the element x belongs to.
  • Union(x, y): merge the two groups that the two elements belong to respectively.
class DisjointSetUnion(object):
	
    def __init__(self, size) :
    	self.parent = [i for i in range(size+1)]
        self.size = [1]*(size+1)
        
    def find(self, x):
    	if self.parent[x] != x :
        	self.parent[x] = self.find(self.parent[x])
        return self.parent[x]
        
    def union(self, x, y):
    	px, py = self.find(x), self.find(y)
        
        if px == py :
        	return px
            
        if self.size[px] > self.size[py] :
        	px, py = py, px
            
        self.parent[px] = py
        self.size[py] += self.size[px]
        
        return py
        
반응형

'0 > algorithm' 카테고리의 다른 글

Greedy algorithm  (0) 2020.09.09
Trie  (0) 2020.05.24
힙 정렬  (0) 2020.05.14
N-Queens  (0) 2019.03.26
Coin Change (DP)  (0) 2019.03.23