- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我想在加权有向图上找到最小生成树 (MST)。我一直在尝试使用 Chu-Liu/Edmond's algorithm ,我已经用 Python 实现了(下面的代码)。可以找到对该算法的简单、清晰的描述 here .我有两个问题。
Edmond 的算法是否保证收敛于一个解?
我担心删除一个循环会添加另一个循环。如果发生这种情况,该算法将继续尝试永远删除循环。
我似乎找到了一个发生这种情况的例子。输入图如下所示(在代码中)。该算法永远不会完成,因为它在循环 [1,2] 和 [1,3] 以及 [5,4] 和 [5,6] 之间切换。添加到图中以解决循环 [5,4] 的边会创建循环 [5,6],反之亦然,对于 [1,2] 和 [1,3] 也是如此。
请注意,我不确定我的实现是否正确。
为了解决这个问题,我引入了一个临时补丁。当删除边以删除循环时,我会从我们正在其上搜索 MST 的基础图 G 中永久删除该边。因此,不能再次添加该边,这应该可以防止算法卡住。有了这个变化,我能保证找到 MST 吗?
我怀疑有人可以找到一个病理案例,其中这一步会导致不是 MST 的结果,但我一直想不出一个。它似乎适用于我尝试过的所有简单测试用例。
代码:
import sys
# --------------------------------------------------------------------------------- #
def _reverse(graph):
r = {}
for src in graph:
for (dst,c) in graph[src].items():
if dst in r:
r[dst][src] = c
else:
r[dst] = { src : c }
return r
# Finds all cycles in graph using Tarjan's algorithm
def strongly_connected_components(graph):
"""
Tarjan's Algorithm (named for its discoverer, Robert Tarjan) is a graph theory algorithm
for finding the strongly connected components of a graph.
Based on: http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
"""
index_counter = [0]
stack = []
lowlinks = {}
index = {}
result = []
def strongconnect(node):
# set the depth index for this node to the smallest unused index
index[node] = index_counter[0]
lowlinks[node] = index_counter[0]
index_counter[0] += 1
stack.append(node)
# Consider successors of `node`
try:
successors = graph[node]
except:
successors = []
for successor in successors:
if successor not in lowlinks:
# Successor has not yet been visited; recurse on it
strongconnect(successor)
lowlinks[node] = min(lowlinks[node],lowlinks[successor])
elif successor in stack:
# the successor is in the stack and hence in the current strongly connected component (SCC)
lowlinks[node] = min(lowlinks[node],index[successor])
# If `node` is a root node, pop the stack and generate an SCC
if lowlinks[node] == index[node]:
connected_component = []
while True:
successor = stack.pop()
connected_component.append(successor)
if successor == node: break
component = tuple(connected_component)
# storing the result
result.append(component)
for node in graph:
if node not in lowlinks:
strongconnect(node)
return result
def _mergeCycles(cycle,G,RG,g,rg):
allInEdges = [] # all edges entering cycle from outside cycle
minInternal = None
minInternalWeight = sys.maxint
# Find minimal internal edge weight
for n in cycle:
for e in RG[n]:
if e in cycle:
if minInternal is None or RG[n][e] < minInternalWeight:
minInternal = (n,e)
minInternalWeight = RG[n][e]
continue
else:
allInEdges.append((n,e)) # edge enters cycle
# Find the incoming edge with minimum modified cost
# modified cost c(i,k) = c(i,j) - (c(x_j, j) - min{j}(c(x_j, j)))
minExternal = None
minModifiedWeight = 0
for j,i in allInEdges: # j is vertex in cycle, i is candidate vertex outside cycle
xj, weight_xj_j = rg[j].popitem() # xj is vertex in cycle that currently goes to j
rg[j][xj] = weight_xj_j # put item back in dictionary
w = RG[j][i] - (weight_xj_j - minInternalWeight) # c(i,k) = c(i,j) - (c(x_j, j) - min{j}(c(x_j, j)))
if minExternal is None or w <= minModifiedWeight:
minExternal = (j,i)
minModifiedWeight = w
w = RG[minExternal[0]][minExternal[1]] # weight of edge entering cycle
xj,_ = rg[minExternal[0]].popitem() # xj is vertex in cycle that currently goes to j
rem = (minExternal[0], xj) # edge to remove
rg[minExternal[0]].clear() # popitem() should delete the one edge into j, but we ensure that
# Remove offending edge from RG
# RG[minExternal[0]].pop(xj, None) #highly experimental. throw away the offending edge, so we never get it again
if rem[1] in g:
if rem[0] in g[rem[1]]:
del g[rem[1]][rem[0]]
if minExternal[1] in g:
g[minExternal[1]][minExternal[0]] = w
else:
g[minExternal[1]] = { minExternal[0] : w }
rg = _reverse(g)
# --------------------------------------------------------------------------------- #
def mst(root,G):
""" The Chu-Liu/Edmond's algorithm
arguments:
root - the root of the MST
G - the graph in which the MST lies
returns: a graph representation of the MST
Graph representation is the same as the one found at:
http://code.activestate.com/recipes/119466/
Explanation is copied verbatim here:
The input graph G is assumed to have the following
representation: A vertex can be any object that can
be used as an index into a dictionary. G is a
dictionary, indexed by vertices. For any vertex v,
G[v] is itself a dictionary, indexed by the neighbors
of v. For any edge v->w, G[v][w] is the length of
the edge.
"""
RG = _reverse(G)
g = {}
for n in RG:
if len(RG[n]) == 0:
continue
minimum = sys.maxint
s,d = None,None
for e in RG[n]:
if RG[n][e] < minimum:
minimum = RG[n][e]
s,d = n,e
if d in g:
g[d][s] = RG[s][d]
else:
g[d] = { s : RG[s][d] }
cycles = [list(c) for c in strongly_connected_components(g)]
cycles_exist = True
while cycles_exist:
cycles_exist = False
cycles = [list(c) for c in strongly_connected_components(g)]
rg = _reverse(g)
for cycle in cycles:
if root in cycle:
continue
if len(cycle) == 1:
continue
_mergeCycles(cycle, G, RG, g, rg)
cycles_exist = True
return g
# --------------------------------------------------------------------------------- #
if __name__ == "__main__":
# an example of an input that works
root = 0
g = {0: {1: 23, 2: 22, 3: 22}, 1: {2: 1, 3: 1}, 3: {1: 1, 2: 0}}
# an example of an input that causes infinite cycle
root = 0
g = {0: {1: 17, 2: 16, 3: 19, 4: 16, 5: 16, 6: 18}, 1: {2: 3, 3: 3, 4: 11, 5: 10, 6: 12}, 2: {1: 3, 3: 4, 4: 8, 5: 8, 6: 11}, 3: {1: 3, 2: 4, 4: 12, 5: 11, 6: 14}, 4: {1: 11, 2: 8, 3: 12, 5: 6, 6: 10}, 5: {1: 10, 2: 8, 3: 11, 4: 6, 6: 4}, 6: {1: 12, 2: 11, 3: 14, 4: 10, 5: 4}}
h = mst(int(root),g)
print h
for s in h:
for t in h[s]:
print "%d-%d" % (s,t)
最佳答案
不要做临时补丁。我承认实现收缩/取消收缩逻辑并不直观,并且递归在某些情况下是不可取的,所以这里有一个适当的 Python 实现,可以提高生产质量。我们不是在每个递归级别执行解收缩步骤,而是将其推迟到最后并使用深度优先搜索,从而避免递归。 (这种修改的正确性最终来自互补松弛,线性规划理论的一部分。)
下面的命名约定是 _rep
表示一个 super 节点(即,一个或多个合约节点的 block )。
#!/usr/bin/env python3
from collections import defaultdict, namedtuple
Arc = namedtuple('Arc', ('tail', 'weight', 'head'))
def min_spanning_arborescence(arcs, sink):
good_arcs = []
quotient_map = {arc.tail: arc.tail for arc in arcs}
quotient_map[sink] = sink
while True:
min_arc_by_tail_rep = {}
successor_rep = {}
for arc in arcs:
if arc.tail == sink:
continue
tail_rep = quotient_map[arc.tail]
head_rep = quotient_map[arc.head]
if tail_rep == head_rep:
continue
if tail_rep not in min_arc_by_tail_rep or min_arc_by_tail_rep[tail_rep].weight > arc.weight:
min_arc_by_tail_rep[tail_rep] = arc
successor_rep[tail_rep] = head_rep
cycle_reps = find_cycle(successor_rep, sink)
if cycle_reps is None:
good_arcs.extend(min_arc_by_tail_rep.values())
return spanning_arborescence(good_arcs, sink)
good_arcs.extend(min_arc_by_tail_rep[cycle_rep] for cycle_rep in cycle_reps)
cycle_rep_set = set(cycle_reps)
cycle_rep = cycle_rep_set.pop()
quotient_map = {node: cycle_rep if node_rep in cycle_rep_set else node_rep for node, node_rep in quotient_map.items()}
def find_cycle(successor, sink):
visited = {sink}
for node in successor:
cycle = []
while node not in visited:
visited.add(node)
cycle.append(node)
node = successor[node]
if node in cycle:
return cycle[cycle.index(node):]
return None
def spanning_arborescence(arcs, sink):
arcs_by_head = defaultdict(list)
for arc in arcs:
if arc.tail == sink:
continue
arcs_by_head[arc.head].append(arc)
solution_arc_by_tail = {}
stack = arcs_by_head[sink]
while stack:
arc = stack.pop()
if arc.tail in solution_arc_by_tail:
continue
solution_arc_by_tail[arc.tail] = arc
stack.extend(arcs_by_head[arc.tail])
return solution_arc_by_tail
print(min_spanning_arborescence([Arc(1, 17, 0), Arc(2, 16, 0), Arc(3, 19, 0), Arc(4, 16, 0), Arc(5, 16, 0), Arc(6, 18, 0), Arc(2, 3, 1), Arc(3, 3, 1), Arc(4, 11, 1), Arc(5, 10, 1), Arc(6, 12, 1), Arc(1, 3, 2), Arc(3, 4, 2), Arc(4, 8, 2), Arc(5, 8, 2), Arc(6, 11, 2), Arc(1, 3, 3), Arc(2, 4, 3), Arc(4, 12, 3), Arc(5, 11, 3), Arc(6, 14, 3), Arc(1, 11, 4), Arc(2, 8, 4), Arc(3, 12, 4), Arc(5, 6, 4), Arc(6, 10, 4), Arc(1, 10, 5), Arc(2, 8, 5), Arc(3, 11, 5), Arc(4, 6, 5), Arc(6, 4, 5), Arc(1, 12, 6), Arc(2, 11, 6), Arc(3, 14, 6), Arc(4, 10, 6), Arc(5, 4, 6)], 0))
关于python - Chu-Liu Edmond 的有向图最小生成树算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23988236/
滑动窗口限流 滑动窗口限流是一种常用的限流算法,通过维护一个固定大小的窗口,在单位时间内允许通过的请求次数不超过设定的阈值。具体来说,滑动窗口限流算法通常包括以下几个步骤: 初始化:设置窗口
表达式求值:一个只有+,-,*,/的表达式,没有括号 一种神奇的做法:使用数组存储数字和运算符,先把优先级别高的乘法和除法计算出来,再计算加法和减法 int GetVal(string s){
【算法】前缀和 题目 先来看一道题目:(前缀和模板题) 已知一个数组A[],现在想要求出其中一些数字的和。 输入格式: 先是整数N,M,表示一共有N个数字,有M组询问 接下来有N个数,表示A[1]..
1.前序遍历 根-左-右的顺序遍历,可以使用递归 void preOrder(Node *u){ if(u==NULL)return; printf("%d ",u->val);
先看题目 物品不能分隔,必须全部取走或者留下,因此称为01背包 (只有不取和取两种状态) 看第一个样例 我们需要把4个物品装入一个容量为10的背包 我们可以简化问题,从小到大入手分析 weightva
我最近在一次采访中遇到了这个问题: 给出以下矩阵: [[ R R R R R R], [ R B B B R R], [ B R R R B B], [ R B R R R R]] 找出是否有任
我正在尝试通过 C++ 算法从我的 outlook 帐户发送一封电子邮件,该帐户已经打开并记录,但真的不知道从哪里开始(对于 outlook-c++ 集成),谷歌也没有帮我这么多。任何提示将不胜感激。
我发现自己像这样编写了一个手工制作的 while 循环: std::list foo; // In my case, map, but list is simpler auto currentPoin
我有用于检测正方形的 opencv 代码。现在我想在检测正方形后,代码运行另一个命令。 代码如下: #include "cv.h" #include "cxcore.h" #include "high
我正在尝试模拟一个 matlab 函数“imfill”来填充二进制图像(1 和 0 的二维矩阵)。 我想在矩阵中指定一个起点,并像 imfill 的 4 连接版本那样进行洪水填充。 这是否已经存在于
我正在阅读 Robert Sedgewick 的《C++ 算法》。 Basic recurrences section it was mentioned as 这种循环出现在循环输入以消除一个项目的递
我正在思考如何在我的日历中生成代表任务的数据结构(仅供我个人使用)。我有来自 DBMS 的按日期排序的任务记录,如下所示: 买牛奶(18.1.2013) 任务日期 (2013-01-15) 任务标签(
输入一个未排序的整数数组A[1..n]只有 O(d) :(d int) 计算每个元素在单次迭代中出现在列表中的次数。 map 是balanced Binary Search Tree基于确保 O(nl
我遇到了一个问题,但我仍然不知道如何解决。我想出了如何用蛮力的方式来做到这一点,但是当有成千上万的元素时它就不起作用了。 Problem: Say you are given the followin
我有一个列表列表。 L1= [[...][...][.......].......]如果我在展平列表后获取所有元素并从中提取唯一值,那么我会得到一个列表 L2。我有另一个列表 L3,它是 L2 的某个
我们得到二维矩阵数组(假设长度为 i 和宽度为 j)和整数 k我们必须找到包含这个或更大总和的最小矩形的大小F.e k=7 4 1 1 1 1 1 4 4 Anwser是2,因为4+4=8 >= 7,
我实行 3 类倒制,每周换类。顺序为早类 (m)、晚类 (n) 和下午类 (a)。我固定的订单,即它永远不会改变,即使那个星期不工作也是如此。 我创建了一个函数来获取 ISO 周数。当我给它一个日期时
假设我们有一个输入,它是一个元素列表: {a, b, c, d, e, f} 还有不同的集合,可能包含这些元素的任意组合,也可能包含不在输入列表中的其他元素: A:{e,f} B:{d,f,a} C:
我有一个子集算法,可以找到给定集合的所有子集。原始集合的问题在于它是一个不断增长的集合,如果向其中添加元素,我需要再次重新计算它的子集。 有没有一种方法可以优化子集算法,该算法可以从最后一个计算点重新
我有一个包含 100 万个符号及其预期频率的表格。 我想通过为每个符号分配一个唯一(且前缀唯一)的可变长度位串来压缩这些符号的序列,然后将它们连接在一起以表示序列。 我想分配这些位串,以使编码序列的预
我是一名优秀的程序员,十分优秀!