GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — Algorithms/mst.py at master · irwenqiang/Algorithms Expand file tree/ Copy pathmst.pyMore file actions 56 lines (51 loc) · 1.06 KB / Copy pathmst.pyFile metadata and controls56 lines (51 loc) · 1.06 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 class dset(object): """A data structure for disjoint sets.""" def __init__(self, n): self.parent = range(n) self.rank = [0] * n def __len__(self): return len(self.parent) def union(self, x, y): rx = self.find(x) ry = self.find(y) if rx == ry: return if self.rank[rx] > self.rank[ry]: self.parent[ry] = rx else: self.parent[rx] = ry if self.rank[rx] == self.rank[ry]: self.rank[ry] += 1 def find(self, x): if x != self.parent[x]: self.parent[x] = self.find(self.parent[x]) return self.parent[x] """ I've changed the way to save a graph. G = (V ,E); which for example: V = a, b, c, d, e, f = range(6) E = { (a, b):2, (a, c):1, (b, c):2, (b, d):1, (c, d):2, (c, e):3, (d, e):3, (d, f):4, (e, f):1 } """ def kruskal(G): """Input: A connected undirected graph G=(V, E) with edge weights Output: A minimum spanning tree defined by the edges X """ V , E = G d = dset(len(V)) X = set([]) E_sorted = list(sorted(E, key=lambda k:E[k])) for u, v in E_sorted: if d.find(u) != d.find(v): X.add((u, v)) d.union(u, v) return X |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |