算法课_unionfind_并查集

来源:互联网 发布:linux 驱动开发 编辑:程序博客网 时间:2024/06/07 17:27

并查集


连接的定义:

1. a连接b,则b连接a。对称性

2. a连接b,b连接c,则a连接c。传递性


并查集的作用:判断两个点是否连接;找出所有连接着的集合


应用举例:

连通,10x10的网格,白表示空,黑表示障碍,是否有一条路从第一行走到第十行?

转化为:是否存在第一行中的任意一点A,第十行的任意一点B,AB是连接的。

对每一个点,将他上下左右相邻的点的连接与否做成并查集。


coursera算法课的面试题:

下面提到的unionfind,union,connect,sz,id等是算法课中unionfind类的变量或者方法。

Question 1

Social network connectivity. Given a social network containing N members and a log file containing M timestamps at which times pairs of members formed friendships, design an algorithm to determine the earliest time at which all members are connected (i.e., every member is a friend of a friend of a friend ... of a friend). Assume that the log file is sorted by timestamp and that friendship is an equivalence relation. The running time of your algorithm should be MlogN or better and use extra space proportional to N.

每connect一次,update size数组时,判断是否size[]==N,则全连。

Question 2

Union-find with specific canonical element. Add a method find() to the union-find data type so that find(i) returns the largest element in the connected component containing i. The operations, union()connected(), and find() should all take logarithmic time or better.


For example, if one of the connected components is {1,2,6,9}, then the find() method should return 9 for each of the four elements in the connected components.

加一个数组mx[i]表示以i为root的的数的max节点值;find的时候先find root,然后再mx[root]

Question 3

Successor with delete. Given a set of N integers S={0,1,...,N1} and a sequence of requests of the following form:

  • Remove x from S

  • Find the successor of x: the smallest y in S such that yx.
design a data type so that all operations (except construction) should take logarithmic time or better.
上一个题目的应用。
使用一个数组rm[]表示是否x是否rm掉。
remove(x){rm[x]=0;if(x+1==0)uf.union(x,x+1);if(x-1==0)uf.union(x,x-1)}
使用一个unionfind来完成第二个request。
findsuccessor(x){if(rm[x]==0)findmx(x)+1;else x;}

Question 4

Union-by-size. Develop a union-find implementation that uses the same basic strategy as weighted quick-union but keeps track of tree height and always links the shorter tree to the taller one. Prove a lgN upper bound on the height of the trees for N sites with your algorithm.
用ht[]代替sz[]

原创粉丝点击