Printing out nodes in a disjoint-set data structure in linear time

我只是一个虾纸丫 提交于 2019-12-21 19:57:05

问题


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:

Suppose that we wish to add the operation PRINT-SET(x), which is given a node x and prints all the members of x's set, in any order. Show how we can add just a single attribute to each node in a disjoint-set forest so that PRINT-SET(x) takes time linear in the number of members of x's set, and the asymptotic running times of the other operations are unchanged. Assume that we can print each member of the set in O(1) time.

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. 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.


回答1:


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.

When a singleton set is first created, the node's next pointer points to itself.

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; so this is a O(1) operation.

To list all the elements in the set containing node X, traverse the circular linked list starting from X.



来源:https://stackoverflow.com/questions/22945058/printing-out-nodes-in-a-disjoint-set-data-structure-in-linear-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!