所有最小生成树的实现
我一直在寻找一个实现(我正在使用 networkx 库。)它将找到所有最小跨度无向加权图的树(MST)。
我只能找到 Kruskal 算法和 Prim 算法的实现,这两个算法都只会返回一个 MST。
我看过解决这个问题的论文(例如 代表所有最小生成树都具有计数和生成的应用),但在尝试思考如何将其转换为代码时,我的头脑往往会以某种方式爆炸。
事实上,我还没有找到任何语言的实现!
I've been looking for an implementation (I'm using networkx library.) that will find all the minimum spanning trees (MST) of an undirected weighted graph.
I can only find implementations for Kruskal's Algorithm and Prim's Algorithm both of which will only return a single MST.
I've seen papers that address this problem (such as Representing all minimum spanning trees with applications to counting and generation) but my head tends to explode someway through trying to think how to translate it to code.
In fact i've not been able to find an implementation in any language!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我不知道这是否是解决方案,但它是解决方案(我想说,这是暴力破解的图形版本):
O(Elog(V) + V + n) 中完成,其中 n = 生成树的数量
,据我从 2 分钟的谷歌了解,可能可以改进。注意:请懒惰地执行此操作!生成所有可能的树,然后过滤结果将占用 O(V^2) 内存,并且多项式空间要求是邪恶的 - 生成一棵树,检查它的权重,如果它是 MST,则将其添加到结果列表中,如果不是 - 丢弃它.
总体时间复杂度:对于具有 n 个生成树的 G(V,E),O(Elog(V) + V + n)
I don't know if this is the solution, but it's a solution (it's the graph version of a brute force, I would say):
O(Elog(V) + V + n) for n = number of spanning trees
, as I understand from 2 minutes's worth of google, can possibly be improved.Note: Do this lazily! Generating all possible trees and then filtering the results will take O(V^2) memory, and polynomial space requirements are evil - Generate a tree, examine it's weight, if it's an MST add it to a result list, if not - discard it.
Overall time complexity:
O(Elog(V) + V + n) for G(V,E) with n spanning trees
Ronald Rivest 在 Python 中有一个很好的实现,mst.py
Ronald Rivest has a nice implementation in Python, mst.py
您可以在 Sorensen 和 Janssens (2005) 的著作中找到想法。
这个想法是按升序生成 ST,一旦获得较大的 ST 值就停止枚举。
You can find an idea in the work of Sorensen and Janssens (2005).
The idea is to generate the STs in the increasing order, and as soon as you get the bigger value of ST stop the enumeration.
这是一个简短的 Python 实现,基本上是 Kruskal 的递归变体。使用找到的第一个 MST 的权重来限制此后搜索空间的大小。绝对仍然是指数复杂度,但比生成每个生成树更好。还包括一些测试代码。
[注意:这只是我自己的实验,目的是为了好玩,并可能从其他人那里获得对问题的进一步思考的灵感,并不是试图具体实施此处提供的其他答案中建议的任何解决方案]
Here's a short python implementation, basically a recursive variation of Kruskal's. Uses weight of the the first MST found to limit the size of the search space thereafter. Definitely still exponential complexity but better than generating every spanning tree. Some test code is also included.
[Note: this was just my own experimentation for fun and possible inspiration of further thoughts on the problem from others, it's not an attempt to specifically implement any of the solutions suggested in other supplied answers here]