算法课_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[]

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值