Union-Find disjoint-set algorithm

A dynamic connectivity (Dynamic Connectivity)

Union-Find algorithm (Chinese called disjoint-set algorithm) is an algorithm to solve dynamic connectivity (Dynamic Conectivity) problem. Dynamic connectivity data structure is a computer graph theory, dynamic maintenance information is connected to the structure of FIG. Simply put, the number of the connected component if left connected between the respective nodes, how to connect the two nodes, connected after. A bit like our micro-channel circle of friends, in a social network, they form their own circle between people know each other, will be added after the familiar friends, adding a new circle. Micro-channel users have hundreds of millions, how to quickly calculate whether any two users belong to the same circle it? Two computer users is how to connect it? There are entire micro-channel user several separate circle it? Union-Find can solve these problems.


Second, the basic concepts
in conjunction with the following example to understand the basic concept of FIG:
 
Figure eight nodes are communicating mutually independent, i.e., a total of eight communication component.

Communication is an equivalence relation, i.e. having the following three properties:

1, reflexivity: node pand pis connected.

2, the symmetry of: if the node pand qcommunicating, then q, and pis also in communication.

3, transitive: if the node pand qcommunicating, qand rcommunicating, then p, and ris also in communication.

If nodes 1 and 2 are connected, and that on the remaining seven connected components, as shown below:
How does it work in these calculations?
class UF:
    def union(self,p,q): # initialize N sites with integer names
    def connected(self,p,q): #return true if p and q are in the same component
    def count(): #number of components

 

 

Guess you like

Origin www.cnblogs.com/gczr/p/12077934.html