1 11 package org.eclipse.ui.internal.ide.misc; 12 13 import java.util.HashMap ; 14 import java.util.Iterator ; 15 import java.util.List ; 16 17 33 public class DisjointSet { 34 38 private static class Node { 39 40 int rank; 41 42 Object parent; 43 44 Node(Object parent, int rank) { 45 this.parent = parent; 46 this.rank = rank; 47 } 48 } 49 50 55 private final HashMap objectsToNodes = new HashMap (); 56 57 64 public Object findSet(Object o) { 65 DisjointSet.Node node = (DisjointSet.Node) objectsToNodes.get(o); 66 if (node == null) 67 return null; 68 if (o != node.parent) 69 node.parent = findSet(node.parent); 70 return node.parent; 71 } 72 73 78 public void makeSet(Object o) { 79 objectsToNodes.put(o, new Node(o, 0)); 80 } 81 82 86 public void removeSet(Object o) { 87 Object set = findSet(o); 88 if (set == null) 89 return; 90 for (Iterator it = objectsToNodes.keySet().iterator(); it.hasNext();) { 91 Object next = it.next(); 92 if (next != set && findSet(next) == set) 94 it.remove(); 95 } 96 objectsToNodes.remove(set); 97 } 98 99 103 public void toList(List list) { 104 list.addAll(objectsToNodes.keySet()); 105 } 106 107 114 public void union(Object x, Object y) { 115 Object setX = findSet(x); 116 Object setY = findSet(y); 117 if (setX == null || setY == null || setX == setY) 118 return; 119 DisjointSet.Node nodeX = (DisjointSet.Node) objectsToNodes.get(setX); 120 DisjointSet.Node nodeY = (DisjointSet.Node) objectsToNodes.get(setY); 121 if (nodeX.rank > nodeY.rank) { 123 nodeY.parent = x; 124 } else { 125 nodeX.parent = y; 126 if (nodeX.rank == nodeY.rank) 127 nodeY.rank++; 128 } 129 } 130 } | Popular Tags |