Union-Find Algorithm

Union-Find Algrithm is used to check whether two components are connected or not.

Examples:

By using the graph, we can easily find whether two components are connected or not, if there is no such graph, how do we know whether two components are connected or not?

Answer: For all connected components, we set their "root" to be the same.

So, we use an array to record the root of each component, if their roots are the same, return true, otherwise, return false.

Example:

So, how to implement it? 

How is the time complexity of the operations?

So, Union operation is kind of expensive, can we decrease it?

Yes, instead of making all the components use the same root id, we can just set the parent id of root component in one set to the root id of another set. (Why we cannot just set the parent id of the root component in one set to the id of the connected component in another set???)

Example:

But the problem is when we check whether two components have the same root, the worst case time complexity is O(n). n refers to the size of the components, and this happens when we have a thin tree (all components are in the same tree, but this tree has no branches.)

Time complexity:

So, the approach above cannot decrease the union operation time complexity, rather, it increases the find operation time complexity.

If we have a closer look, we can find the reason why quick-union approach is not performing well is because the height of the tree could be very tall. So, the question becomes how to decrease the height of th tree?

There are two approaches:

First, when we marge two trees, the root of the smaller tree (with less # of components) will be connected to the root of larger tree.

The benefit of doing this can decrease the height of the tree.

Another approach is called path compression. The idea is every time when we get the root of a component, we always set its parent id to the root id. 

Example:

So, this approach can also decrease the height of the tree.

Reference:https://www.cs.duke.edu/courses/cps100e/fall09/notes/UnionFind.pdf (普林斯顿的这位老爷爷讲得真的很清楚,youtube上可以收到他的视频。)

转载于:https://www.cnblogs.com/beiyeqingteng/p/5751608.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值