Kruskal(克魯斯卡爾)

來源:互聯網
上載者:User

 

設有一個有n個頂點的連通網N={V,E},最初先構造一個只有n個頂點, 沒有邊的非 連通圖 T={V,
E},
圖中每個頂點自成一個連通分量。 當在E中選到一條具有最小權值的邊時,若該邊的兩個頂點落在不同的連通分量上, 則將此邊加入到T中;否則將此邊捨去,重新選擇一條權值最小的邊。 如此重複下去,直到所有頂點在同一個連通分量上為止。

 

 

import java.io.BufferedInputStream;import java.util.*;/* * @author denghuilong  *   * 2013-8-7上午11:36:00 * */public class Kruskal {public static int n = 9;// 九個頂點public static int patten[];public static void main(String args[]) {ArrayList<Edge> ay = new ArrayList<Edge>();Edge p0 = new Edge(0, 1, 10);Edge p1 = new Edge(0, 5, 11);Edge p2 = new Edge(1, 8, 12);Edge p3 = new Edge(1, 2, 18);Edge p4 = new Edge(1, 6, 16);Edge p5 = new Edge(2, 8, 8);Edge p6 = new Edge(2, 3, 22);Edge p7 = new Edge(3, 4, 20);Edge p8 = new Edge(3, 7, 16);Edge p9 = new Edge(3, 6, 24);Edge p10 = new Edge(3, 8, 21);Edge p11 = new Edge(4, 7, 7);Edge p12 = new Edge(4, 5, 26);Edge p13 = new Edge(5, 6, 17);Edge p14 = new Edge(6, 7, 19);ay.add(p0);ay.add(p1);ay.add(p2);ay.add(p3);ay.add(p4);ay.add(p5);ay.add(p6);ay.add(p7);ay.add(p8);ay.add(p9);ay.add(p10);ay.add(p11);ay.add(p12);ay.add(p13);ay.add(p14);System.out.println("按權值排序");Collections.sort(ay);for (Edge pp : ay) {System.out.println(pp);}System.out.println("Kruskal(克魯斯卡爾)");int sum = 0;patten = new int[n + 1];for (int i = 1; i <= n; i++) {patten[i] = i;}int i = 0;while (ay.size() > 0) {int jj = patten[ay.get(0).start];int kk = patten[ay.get(0).end];if (jj != kk) {i++;sum += ay.get(0).num;fun(jj, kk);}System.out.println(ay.get(0));ay.remove(ay.get(0));}}public static void fun(int j, int k) {for (int i = 1; i <= n; ++i) {if (patten[i] == j) {patten[i] = k;}}}}class Edge implements Comparable<Edge> {public int start;public int end;public int num;public Edge(int start, int end, int num) {this.start = start;this.end = end;this.num = num;}public int compareTo(Edge o) {return this.num > o.num ? 1 : -1;}public String toString() {return "[" + start + "," + end + "," + num + "]";}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.