启发式优化的不相交集实现(按秩和路径压缩的联合)
dset的Python项目详细描述
a不相交集实现,它使用“按秩并集”和“路径压缩”启发式 尽可能简单有效地进行优化。
它支持以下操作:
- find set在o(1)摊销运行时间中
- union在o(1)摊销运行时间中
check end notes了解有关运行时间的其他信息
为什么?
有时,特别是在算法竞赛中,需要联合查找数据结构 在这种情况下,为了解决某个问题(例如,在实现kruskal的mst算法时), 我们通常使用pypi中的现成实现,而且,很多时候, 我们得到了臭名昭著的提交失败时间限制超过(tle),因为 不相交集的实现不够快…
别担心!一个足够快速和简单(可以复制粘贴代码here)的不相交集实现 现在可用:
安装
$ pip install dset
用法
>>>importdset>>>s1=dset.Set()# To create new sets objects (it runs in O(1))>>>s2=dset.Set()>>>s3=dset.Set()>>>dset.groups()# To check the number of different groups (it runs in O(1))3>>>dset.find(s1)==dset.find(s2)# To check if two sets are in the same groupFalse>>>dset.union(s1,s2)# to group s1 and s2 sets together>>>dset.groups()# Now there are only 2 groups: s1-s2 and s32>>>dset.find(s1)==dset.find(s2)# They are in the same group s1-s2True>>>dset.find(s2)==dset.find(s3)# They are in distinct groups s1-s2 and s3False>>>dset.union(s2,s1)# do nothing (no need to check if s1 and s2 belong to the same group)>>>dset.groups()# Same as before only 2: s1-s2 and s32>>>dset.union(s1,s3)# group s1-s2 and s3 together.>>>dset.groups()# Now there is only one group: s1-s2-s31>>>dset.find(s1)==dset.find(s2)# All the sets are in the same groups s1-s2-s3...dset.find(s2)==dset.find(s3)...dset.find(s1)==dset.find(s3)TrueTrueTrue
未来改进
- 制作狮身人面像官方文件。(小版本)
- 制作测试套件。(小版本)
- 更改为基于列表的实现(主要版本和次要版本)
- 提高运行时间(常数项)
- 提高存储空间(常数项)
- 使包基于c。(主要次要版本)
- 提高运行时间(常数项)
另外,“按列合并”或“路径压缩”都可以提高 不相交集上的运算。单独地,“按等级联合”产生一个运行时间 其中,m是并集和查找集操作的数目,n是数目 一套接一套。
当我们同时使用这两种启发式方法时,改进会更大;最坏的情况是 时间是o(m f(n)),其中f(n)是一个非常缓慢增长的函数,逆ackermann函数 (例如,如果n等于宇宙中的原子数,f(n)仅为4) 因此,对于任何可能的应用程序,我们可以考虑munion+find set操作的运行时间为 o(m)因此union和find set操作实际上都有o(1)摊销运行时间。