我已经为这个问题写了一些代码。(python27)
图形表示为具有 freezeset 键和 freezeset 集的字典:
sample_graph = {frozenset([7]): set([frozenset([4]), frozenset([5]), frozenset([3])]), frozenset([5]): set([frozenset([7]), frozenset([2]), frozenset([1])]), frozenset([3]): set([frozenset([7]), frozenset([4]), frozenset([2]), frozenset([1])]), frozenset([6]): set([frozenset([4]), frozenset([2]), frozenset([1])]), frozenset([4]): set([frozenset([6]), frozenset([7]), frozenset([3]), frozenset([1])]), frozenset([1]): set([frozenset([6]), frozenset([4]), frozenset([5]), frozenset([2]), frozenset([3])]), frozenset([2]): set([frozenset([6]), frozenset([5]), frozenset([3]), frozenset([1])])}
输出应该是一个只有两个节点的图,它们是图中所有节点的冻结集。此时它会遇到 KeyError。
def kargerMinCut(graph):
if len(graph) == 2:
return graph
u = random.choice(graph.keys()) # u and v are frozensets, idea is that they form
v = random.choice(list(graph[u])) # a clique in a single frozenset
for node in graph:
if node != u and node != v:
links = graph[node]
if u in links or v in links:
links.add(frozenset(tuple(u | v))) # combine u and v to form one link
links.discard(u) # delete old links to u and v
links.discard(v)
graph[node] = links
graph[u | v] = graph[u] | graph[v] # new key for u and v
del graph[u], graph[v] # u and v are no longer needed
return kargerMinCut(graph)