码迷,mamicode.com
首页 > 其他好文 > 详细

Union-Find Algorithm

时间:2016-08-09 07:03:33      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:

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上可以收到他的视频。)

Union-Find Algorithm

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5751608.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!