数据结构 - 并查集

#!/usr/bin/env python3.3
# -*- coding:utf-8 -*-
# Copyright 2013

'''
并查集
1)合并两个不相交集合
2)判断两个元素是否属于同一个集合
'''

class UnionFindSet:
    def __init__(self):
        self.root = {}
        self.rank = {}

    def make_set(self, x):
        self.root[x] = x
        self.rank[x] = 0    

    def find(self, x):
        root = self.root
        if x != root[x]:
            root[x] = self.find(root[x])
        return root[x]

    def union(self, x, y):
        root = self.root
        rank = self.rank
        fx = self.find(x)
        fy = self.find(y)
        if fx != fy:
            if rank[fx] > rank[fy]:
                root[fy] = fx
            else:
                root[fx] = fy
                if rank[fx] == rank[fy]:
                    rank[fy] += 1

 

posted @ 2013-04-29 23:35  Leung文  阅读(139)  评论(0编辑  收藏  举报