Advertisement
thinkpad20

algorithms 3 mincut

Apr 16th, 2012
1,117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.43 KB | None | 0 0
  1. import random
  2. import copy
  3.  
  4. filename = "kargerAdj.txt"
  5.  
  6. def makeMaps(filename):
  7.     file1 = open(filename)
  8.     graph = {}
  9.     count = 0
  10.     print "Loading from",filename
  11.     for line in file1:
  12.         node = int(line.split()[0])
  13.         edges = []
  14.         for edge in line.split()[1:]:
  15.             edges.append(int(edge))
  16.         graph[node] = edges
  17.         count += 1
  18.     print len(graph), "vertices in dictionary."
  19.     file1.close()
  20.     return graph
  21.  
  22. graph = makeMaps(filename)
  23.  
  24. cuts = []
  25.  
  26. def karger(graph):
  27.     while len(graph) > 2:
  28.         removed = 0
  29.         added = 0
  30.         start = random.choice(graph.keys())
  31.         finish = random.choice(graph[start])
  32.  
  33.     ## Adding the edges from the absorbed node:
  34.         for edge in graph[finish]:
  35.             if edge != start:# this stops us from making a self-loop
  36.                 graph[start].append(edge)
  37.                
  38.     ## Deleting the references to the absorbed node and changing them to the source node:
  39.         for edge1 in graph[finish]:
  40.             graph[edge1].remove(finish)
  41.             if edge1 != start:# this stops us from re-adding all the edges in start.
  42.                 graph[edge1].append(start)
  43.         del graph[finish]
  44.  
  45.     ## Calculating and recording the mincut
  46.     mincut = len(graph[graph.keys()[0]])
  47.     cuts.append(mincut)
  48.    
  49. for i in range(1,801):
  50.     graph1 = copy.deepcopy(graph)
  51.     karger(graph1)
  52. print "Mincut is", min(cuts)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement