搜尋
首頁Javajava教程最小生成樹

圖的最小生成樹是總權重最小的生成樹。

一個圖可能有許多生成樹。假設邊緣被加權。最小生成樹的總權重最小。例如,下圖 b、c、d 中的樹是圖 a 中圖的生成樹。圖c和d中的樹是最小生成樹。

Minimum Spanning Trees

尋找最小生成樹的問題有很多應用。考慮一家在許多城市設有分公司的公司。該公司希望租用電話線將所有分公司連接在一起。電話公司對連接不同的城市收取不同的費用。有多種方法可以將所有分支連接在一起。最便宜的方法是找出總費率最小的生成樹。

最小生成樹演算法

如何找到最小生成樹?有幾種眾所周知的演算法可以做到這一點。本節介紹Prim演算法。 Prim 的演算法從包含任一頂點的生成樹 T 開始。此演算法透過重複添加具有與樹中已有頂點相關的最低成本邊的頂點來擴展樹。 Prim的演算法是一種貪心演算法,其程式碼如下所示。

Input: A connected undirected weighted G = (V, E) with non-negative weights
 Output: MST (a minimum spanning tree)
 1 MST minimumSpanningTree() {
 2 Let T be a set for the vertices in the spanning tree;
 3 Initially, add the starting vertex to T;
 4
 5 while (size of T 



<p>演算法首先將起始頂點加入<strong>T</strong>中。然後,它不斷地將一個頂點(例如 <strong>v</strong>)從 <strong>V – T</strong> 添加到 <strong>T</strong> 中。 <strong>v</strong> 是與 <strong>T</strong> 中的頂點相鄰且邊權重最小的頂點。例如,<strong>T</strong> 和<strong>V – T</strong> 中的頂點有5 條邊連接,如下圖所示,並且(<strong>u</strong>, <strong>v</strong> ) 是權重最小的一個。 </p>

<p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172557408574612.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Minimum Spanning Trees"></p>

<p>考慮下圖中的圖表。此演算法會以以下順序將頂點加入 <strong>T</strong>:</p>

<p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172557408660759.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Minimum Spanning Trees"></p>

<ol>
<li>將頂點 <strong>0</strong> 加入 <strong>T</strong>。 </li>
<li>將頂點<strong>5</strong> 加到<strong>T</strong>,因為<strong>Edge(5, 0, 5)</strong> 在與T<strong>,如圖a所示。由 </strong>0<strong> 到 </strong>5<strong> 的箭頭線表示 </strong>0<strong> 是 </strong>5<strong> 的父級。 </strong>
</li>將頂點<li>1<strong> 加到</strong>T<strong>,因為</strong>Edge(1, 0, 6)<strong> 在與T</strong>,如圖b.<strong>
</strong>將頂點</li>6<li> 加到<strong>T</strong>,因為<strong>Edge(6, 1, 7)</strong> 在與T<strong>,如圖c.</strong>
<strong>將頂點</strong>2</li>加到<li>T<strong>,因為</strong>邊(2,6,5)<strong>在與T</strong>,如圖d.<strong>
</strong>將頂點<strong>4</strong>加到</li>T<li>,因為<strong>邊(4,6,7)</strong>在與T<strong>,如圖e.</strong>
<strong>將頂點</strong>3<strong>加到</strong>T</li>,因為<li>邊(3,2,8)<strong>在與T</strong>,如圖f.<strong>
</strong>

<strong>最小生成樹不是唯一的。例如,下圖中的 (c) 和 (d) 都是圖 a 中的圖的最小生成樹。但是,如果權重不同,則該圖具有唯一的最小生成樹。 </strong>

<strong></strong>
</li>

</ol>假設圖是連通且無向的。如果圖沒有連通或有向,則演算法將不起作用。您可以修改演算法來尋找任何無向圖的生成林。生成森林是一個圖,其中每個連接的組件都是一棵樹。 <p>

</p><h2>
  
  
  Refining Prim’s MST Algorithm
</h2>

<p>To make it easy to identify the next vertex to add into the tree, we use <strong>cost[v]</strong> to store the cost of adding a vertex <strong>v</strong> to the spanning tree <strong>T</strong>. Initially <strong>cost[s]</strong> is <strong>0</strong> for a starting vertex and assign infinity to <strong>cost[v]</strong> for all other vertices. The algorithm repeatedly finds a vertex <strong>u</strong> in <strong>V – T</strong> with the smallest <strong>cost[u]</strong> and moves <strong>u</strong> to <strong>T</strong>. The refined version of the alogrithm is given in code below.<br>
</p>

<pre class="brush:php;toolbar:false">Input: A connected undirected weighted G = (V, E) with non-negative weights
Output: a minimum spanning tree with the starting vertex s as the root
 1 MST getMinimumSpanngingTree(s) {
 2 Let T be a set that contains the vertices in the spanning tree;
 3 Initially T is empty;
 4 Set cost[s] = 0; and cost[v] = infinity for all other vertices in V;
 5
 6 while (size of T  w(u, v)) { // Adjust cost[v]
11 cost[v] = w(u, v); parent[v] = u;
12 }
13 }
14 }

Implementation of the MST Algorithm

The getMinimumSpanningTree(int v) method is defined in the WeightedGraph class. It returns an instance of the MST class, as shown in Figure below.

Minimum Spanning Trees

The MST class is defined as an inner class in the WeightedGraph class, which extends the Tree class, as shown in Figure below.

Minimum Spanning Trees

The Tree class was shown in Figure below. The MST class was implemented in lines 141–153 in WeightedGraph.java.

Minimum Spanning Trees

The refined version of the Prim’s algoruthm greatly simplifies the implementation. The getMinimumSpanningTree method was implemented using the refined version of the Prim’s algorithm in lines 99–138 in Listing 29.2. The getMinimumSpanningTree(int startingVertex) method sets cost[startingVertex] to 0 (line 105) and cost[v] to infinity for all other vertices (lines 102–104). The parent of startingVertex is set to -1 (line 108). T is a list that stores the vertices added into the spanning tree (line 111). We use a list for T rather than a set in order to record the order of the vertices added to T.

Initially, T is empty. To expand T, the method performs the following operations:

  1. Find the vertex u with the smallest cost[u] (lines 118–123 and add it into T (line 125).
  2. After adding u in T, update cost[v] and parent[v] for each v adjacent to u in V-T if cost[v] > w(u, v) (lines 129–134).

After a new vertex is added to T, totalWeight is updated (line 126). Once all vertices are added to T, an instance of MST is created (line 137). Note that the method will not work if the graph is not connected. However, you can modify it to obtain a partial MST.

The MST class extends the Tree class (line 141). To create an instance of MST, pass root, parent, T, and totalWeight (lines 144-145). The data fields root, parent, and searchOrder are defined in the Tree class, which is an inner class defined in AbstractGraph.

Note that testing whether a vertex i is in T by invoking T.contains(i) takes O(n) time, since T is a list. Therefore, the overall time complexity for this implemention is O(n3).

The code below gives a test program that displays minimum spanning trees for the graph in Figure below and the graph in Figure below a, respectively.

Minimum Spanning Trees

Minimum Spanning Trees

package demo;

public class TestMinimumSpanningTree {

    public static void main(String[] args) {
        String[] vertices = {"Seattle", "San Francisco", "Los Angeles", "Denver", "Kansas City", "Chicago", "Boston", "New York", "Atlanta", "Miami", "Dallas", "Houston"};

        int[][] edges = {
                {0, 1, 807}, {0, 3, 1331}, {0, 5, 2097},
                {1, 0, 807}, {1, 2, 381}, {1, 3, 1267},
                {2, 1, 381}, {2, 3, 1015}, {2, 4, 1663}, {2, 10, 1435},
                {3, 0, 1331}, {3, 1, 1267}, {3, 2, 1015}, {3, 4, 599}, {3, 5, 1003},
                {4, 2, 1663}, {4, 3, 599}, {4, 5, 533}, {4, 7, 1260}, {4, 8, 864}, {4, 10, 496},
                {5, 0, 2097}, {5, 3, 1003}, {5, 4, 533}, {5, 6, 983}, {5, 7, 787},
                {6, 5, 983}, {6, 7, 214},
                {7, 4, 1260}, {7, 5, 787}, {7, 6, 214}, {7, 8, 888},
                {8, 4, 864}, {8, 7, 888}, {8, 9, 661}, {8, 10, 781}, {8, 11, 810},
                {9, 8, 661}, {9, 11, 1187},
                {10, 2, 1435}, {10, 4, 496}, {10, 8, 781}, {10, 11, 239},
                {11, 8, 810}, {11, 9, 1187}, {11, 10, 239}
        };

        WeightedGraph<string> graph1 = new WeightedGraph(vertices, edges);
        WeightedGraph<string>.MST tree1 = graph1.getMinimumSpanningTree();
        System.out.println("Total weight is " + tree1.getTotalWeight());
        tree1.printTree();

        edges = new int[][]{
            {0, 1, 2}, {0, 3, 8},
            {1, 0, 2}, {1, 2, 7}, {1, 3, 3},
            {2, 1, 7}, {2, 3, 4}, {2, 4, 5},
            {3, 0, 8}, {3, 1, 3}, {3, 2, 4}, {3, 4, 6},
            {4, 2, 5}, {4, 3, 6}
        };

        WeightedGraph<integer> graph2 = new WeightedGraph(edges, 5);
        WeightedGraph<integer>.MST tree2 = graph2.getMinimumSpanningTree(1);
        System.out.println("\nTotal weight is " + tree2.getTotalWeight());
        tree2.printTree();
    }

}

</integer></integer></string></string>

Total weight is 6513.0
Root is: Seattle
Edges: (Seattle, San Francisco) (San Francisco, Los Angeles)
(Los Angeles, Denver) (Denver, Kansas City) (Kansas City, Chicago)
(New York, Boston) (Chicago, New York) (Dallas, Atlanta)
(Atlanta, Miami) (Kansas City, Dallas) (Dallas, Houston)

Total weight is 14.0
Root is: 1
Edges: (1, 0) (3, 2) (1, 3) (2, 4)

The program creates a weighted graph for Figure above in line 27. It then invokes getMinimumSpanningTree() (line 28) to return an MST that represents a minimum spanning tree for the graph. Invoking printTree() (line 30) on the MST object displays the edges in the tree. Note that MST is a subclass of Tree. The printTree() method is defined in the Tree class.

The graphical illustration of the minimum spanning tree is shown in Figure below. The vertices are added to the tree in this order: Seattle, San Francisco, Los Angeles, Denver, Kansas City, Dallas, Houston, Chicago, New York, Boston, Atlanta, and Miami.

Minimum Spanning Trees

以上是最小生成樹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
如何將Maven或Gradle用於高級Java項目管理,構建自動化和依賴性解決方案?如何將Maven或Gradle用於高級Java項目管理,構建自動化和依賴性解決方案?Mar 17, 2025 pm 05:46 PM

本文討論了使用Maven和Gradle進行Java項目管理,構建自動化和依賴性解決方案,以比較其方法和優化策略。

如何使用適當的版本控制和依賴項管理創建和使用自定義Java庫(JAR文件)?如何使用適當的版本控制和依賴項管理創建和使用自定義Java庫(JAR文件)?Mar 17, 2025 pm 05:45 PM

本文使用Maven和Gradle之類的工具討論了具有適當的版本控制和依賴關係管理的自定義Java庫(JAR文件)的創建和使用。

如何使用咖啡因或Guava Cache等庫在Java應用程序中實現多層緩存?如何使用咖啡因或Guava Cache等庫在Java應用程序中實現多層緩存?Mar 17, 2025 pm 05:44 PM

本文討論了使用咖啡因和Guava緩存在Java中實施多層緩存以提高應用程序性能。它涵蓋設置,集成和績效優勢,以及配置和驅逐政策管理最佳PRA

如何將JPA(Java持久性API)用於具有高級功能(例如緩存和懶惰加載)的對象相關映射?如何將JPA(Java持久性API)用於具有高級功能(例如緩存和懶惰加載)的對象相關映射?Mar 17, 2025 pm 05:43 PM

本文討論了使用JPA進行對象相關映射,並具有高級功能,例如緩存和懶惰加載。它涵蓋了設置,實體映射和優化性能的最佳實踐,同時突出潛在的陷阱。[159個字符]

Java的類負載機制如何起作用,包括不同的類載荷及其委託模型?Java的類負載機制如何起作用,包括不同的類載荷及其委託模型?Mar 17, 2025 pm 05:35 PM

Java的類上載涉及使用帶有引導,擴展程序和應用程序類負載器的分層系統加載,鏈接和初始化類。父代授權模型確保首先加載核心類別,從而影響自定義類LOA

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
4 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
4 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
4 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
1 個月前By尊渡假赌尊渡假赌尊渡假赌

熱工具

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中