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 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| package bbm.graph;
import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set;
public class Kruskal {
public static class Line { String[] pNames; int w;
public Line(String name1, String name2, int weight) { pNames = new String[] {name1, name2}; w = weight; }
@Override public int hashCode() { return super.hashCode(); }
@Override public boolean equals(Object w) { return super.equals(w); } }
public static void main(String[] args) { List<Line> graphLines = new LinkedList<>(); graphLines.add(new Line("a", "b", 4)); graphLines.add(new Line("a", "h", 8)); graphLines.add(new Line("b", "h", 11)); graphLines.add(new Line("c", "b", 8)); graphLines.add(new Line("h", "g", 1)); graphLines.add(new Line("h", "i", 7)); graphLines.add(new Line("i", "c", 2)); graphLines.add(new Line("i", "g", 6)); graphLines.add(new Line("c", "d", 7)); graphLines.add(new Line("g", "f", 2)); graphLines.add(new Line("c", "f", 4)); graphLines.add(new Line("d", "f", 14)); graphLines.add(new Line("d", "e", 9)); graphLines.add(new Line("e", "f", 10)); graphLines.sort(Comparator.comparingInt(o -> o.w)); Map<String, Set<String>> nodeTrees = new HashMap<>(); for (Line line : graphLines) { if (!nodeTrees.containsKey(line.pNames[0])) { nodeTrees.put(line.pNames[0], new HashSet<>()); nodeTrees.get(line.pNames[0]).add(line.pNames[0]); } if (!nodeTrees.containsKey(line.pNames[1])) { nodeTrees.put(line.pNames[1], new HashSet<>()); nodeTrees.get(line.pNames[1]).add(line.pNames[1]); } if (!nodeTrees.get(line.pNames[1]).equals(nodeTrees.get(line.pNames[0]))) { System.out.println(line.pNames[0] + "-" + line.pNames[1]); nodeTrees.get(line.pNames[1]).addAll(nodeTrees.get(line.pNames[0])); nodeTrees.put(line.pNames[0], nodeTrees.get(line.pNames[1])); for(String node: nodeTrees.get(line.pNames[1])) { nodeTrees.put(node, nodeTrees.get(line.pNames[1])); } } } } }
|