算法課_unionfind_並查集

並查集


連接的定義:

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[]

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章