如何实现由链表不相交集的数据结构?

编程入门 行业动态 更新时间:2024-10-12 18:20:22
本文介绍了如何实现由链表不相交集的数据结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我不知道如何通过链表来Implemente不相交集数据结构?谁可以告诉我吗? 我特别感到困惑如何查找集()可以工作O(1)时间,这样的实现。THX〜

i don't know how to Implemente Disjoint-set data structure by Linked list? who can tell me? i'm especially confused about how can the find-set() can work O(1) time in such implementation。 thx~

推荐答案

虽然不相交集数据结构通常被解释为对本之木,它通常实施使用数组:一个数组的索引映射到指数的父母和一个阵列映射的索引,它的等级。此摆脱了很多无谓的开销(在空间和时间),这是不相关的理论,但它是在实际中。您可能需要一种方法来某种对象的索引和实例之间的映射。

While the disjoint-set data structure is typically explained as a forest of trees, it's typically implemented with arrays: one array to map an index to the index of its parent, and one array to map an index to its rank. This gets rid of a lot of pointless overhead (in both space and time), which isn't relevant in theory, but it is in practice. You may need a way to map between the indexes and instances of some kind of object.

查找不为O(1),由工作方式。跟了上来prevents诀窍查找采取线性时间,但它仍然可以在最坏的情况下步骤的对数数。在O(α(n))的时间是摊销的时间,它的棘手解释它从何而来 - 你可以找到分析的效率不错,但不是线性并集算法[的Tarjan]

find does not work in O(1), by the way. The trick with the ranks prevents find from taking linear time, but it can still take a logarithmic number of steps in the worst case. The O(α(n)) time is an amortized time, and it's tricky to explain where it comes from - you can find the analysis in Efficiency of a Good But Not Linear Set Union Algorithm [Tarjan].

下面是它可以工作的一种方式:

Here's one way it could work:

disjoint_set { int[] parent, rank; makeset(int n) { rank = new int[n]; parent = new int[n]; for(int i = 0; i < n; i++) parent[i] = i; } int find(int i) { if (parent[i] != i) parent[i] = find(parent[i]); return parent[i]; } void union(int x, int y) { x_root = find(x); y_root = find(y); if (x_root != y_root) { if (rank[x_root] < rank[y_root]) parent[x_root] = y_root; else if (rank[x_root] > rank[y_root]) parent[y_root] = x_root; else { parent[y_root] = x_root; rank[x_root]++; } } } }

更多推荐

如何实现由链表不相交集的数据结构?

本文发布于:2023-10-24 20:37:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524945.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据结构   如何实现   链表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!