Prim算法

来源:互联网 发布:mac远程控制 向日葵 编辑:程序博客网 时间:2024/05/21 07:05
package com.data.struct;import java.util.HashSet;import java.util.Iterator;import java.util.Random;import java.util.Set;public class Prim {private Node[] list;private Set<Node> restSet = new HashSet<Node>();private Set<Node> computedSet = new HashSet<Node>();public Prim(int v, int e) {System.out.println("v:" + v + " e:" + e);list = new Node[v];for (int i = 0; i < v; i++) {Node node = new Node();node.id = i;node.key = Integer.MAX_VALUE;list[i] = node;}System.out.print("weight:");for (int i = 0; i < e; i++) {int v1 = new Random().nextInt(v);int v2 = new Random().nextInt(v);if (v1 == v2) {continue;}while (true) {Node node = list[v1];Node x = node;boolean already = false;while (node.next != null) {if (node.next.id == v2) {already = true;break;}node = node.next;}if (already == true) {break;}Node ex = new Node();ex.id = v2;ex.w = new Random().nextInt(e);System.out.print(ex.w + " ");node.next = ex;break;}}System.out.println();}public void prim() {list[0].key = 0;computedSet.add(list[0]);for (int i = 1; i < list.length; i++) {restSet.add(list[i]);}Node w=list[0].next;Node u=list[0];while (w != null) {if(w.w<list[w.id].key){w.parent=u;w.key=w.w;}w = w.next;}while (restSet.size() > 0) { u = extractMin(); if(u==null){ break; }computedSet.add(u); w=u.next;while (w != null) {Iterator<Node> it2 = computedSet.iterator();boolean has = false;while (it2.hasNext()) {if (w.id == it2.next().id) {has = true;break;}}if (!has) {if(w.w<list[w.id].key){list[w.id].parent=u;list[w.id].key=w.w;}}w = w.next;}}}public Node extractMin() {Iterator<Node> it = computedSet.iterator();int id = -1;int minW = Integer.MAX_VALUE;while (it.hasNext()) {Node node = it.next();Node w = node.next;while (w != null) {Iterator<Node> it2 = computedSet.iterator();boolean has = false;while (it2.hasNext()) {if (w.id == it2.next().id) {has = true;break;}}if (!has) {if (minW > w.w) {id = w.id;minW = w.w;}}w = w.next;}}if(id==-1){return null;}return list[id];}public void printG() {for (int i = 0; i < list.length; i++) {Node node = list[i];System.out.print(node.id + "=>");while (node.next != null) {System.out.print(node.next.id + "(" + node.next.w + ")=>");node = node.next;}System.out.println();}}public void printTree(){for(int i=0;i<list.length;i++){Node node=list[i];while(node.parent!=null){  System.out.print(node.id +" ");;  node=node.parent;}System.out.print(node.id+" ");System.out.println();}}public Node findSet(Node x) {if (x.parent != x) {x.parent = findSet(x.parent);}return x.parent;}public static class Node {private int id;private Node next;private int w;private int key;private Node parent;}public static void main(String[] args) {Prim p = new Prim(5, 20);p.printG();p.prim();p.printTree();}}

0 0
原创粉丝点击