[英]Printing out nodes in a disjoint-set data structure in linear time
I'm trying to do this exercise in Introduction to Algorithms by Cormen et al that has to do with the Disjoin Set data structure: 我试图在Cormen等人的算法导论中做这个练习,它与Disjoin Set数据结构有关:
Suppose that we wish to add the operation
PRINT-SET(x)
, which is given a nodex
and prints all the members ofx
's set, in any order.假设我们希望添加操作
PRINT-SET(x)
,该操作给定节点x
并以任何顺序打印x
的集合的所有成员。 Show how we can add just a single attribute to each node in a disjoint-set forest so thatPRINT-SET(x)
takes time linear in the number of members ofx
's set , and the asymptotic running times of the other operations are unchanged.展示我们如何只为一个不相交的林中的每个节点添加一个属性,以便
PRINT-SET(x)
在x
的集合成员数量上花费时间线性,其他操作的渐近运行时间是不变。 Assume that we can print each member of the set in O(1) time.假设我们可以在O(1)时间内打印该组的每个成员。
Now, I'm quite sure that the attribute needed is a tail pointer , so it can keep track of the children. 现在,我非常确定所需的属性是尾指针 ,因此它可以跟踪孩子。
Since the disjoint set structure already has a parent attribute, find-set(x)
can easily print out nodes going in one direction. 由于不相交的集合结构已经具有父属性,因此
find-set(x)
可以轻松地打印出在一个方向上行进的节点。 But now, having a tail pointer, let's us go the other direction as well. 但现在,有一个尾指针,让我们走向另一个方向。
However, I'm not sure how I would write the algorithm to do this. 但是,我不确定如何编写算法来执行此操作。 If anyone could help me out in pseudocode, that would be much appreciated.
如果有人能用伪代码帮助我,那将非常感激。
Each node should have a next
pointer to the next node in the set it is in. The nodes in a set should form a circular linked list . 每个节点都应该有一个指向它所在集合中下一个节点的
next
指针。集合中的节点应该形成一个循环链表 。
When a singleton set is first created, the node's next
pointer points to itself. 首次创建单例集时,节点的
next
指针指向自身。
When you merge set with node X
and set with node Y
(and you've already checked that those sets are different by normalizing to set representatives), you merge the circular linked lists, which you can do by simply swapping X.next
and Y.next
; 当您将集合与节点
X
合并并使用节点Y
设置时(并且您已经通过规范化设置代表来检查这些集合是否不同),您可以合并循环链接列表,只需交换X.next
和Y.next
; so this is a O(1)
operation. 所以这是
O(1)
操作。
To list all the elements in the set containing node X
, traverse the circular linked list starting from X
. 要列出包含节点
X
的集合中的所有元素,请从X
开始遍历循环链接列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.