最小生成樹 kruskal_使用Kruskal算法求解Java最小生成樹問題

最小生成樹 kruskal

In Electronic Circuit we often required less wiring to connect pins together. We can model this wiring problem with a connected, undirected graph G=(V, E), where V is the set of pins, E is the set of possible interconnections between pair of pins, and for each edge we have a weight w(u,v) specifying the cost (amount of wire needed) to connect u and v. We then wish to find an acyclic subset T that connects all of the vertices and whose total weight w(T)= sum of all the weights in T is minimized . Since T is acyclic and connects all of the vertices, it must form a tree, which we call a spanning tree since it spans the graph G. We call this problem minimum spanning tree problem.

在電子電路中,我們通常需要較少的接線來將引腳連接在一起。 我們可以使用連接的無向圖G =(V,E)來建模此布線問題,其中V是引腳組, E是引腳對之間可能的互連集,對于每個邊,我們都有權重w( u,v)指定連接uv的成本(所需的電線數量)。 然后,我們希望找到一個無環子集T ,它連接所有頂點,并且總權重w(T)= T中所有權重的總和最小 。 由于T是無環的并且連接所有頂點,因此它必須形成一棵樹,由于它跨越了圖G ,因此我們將其稱為生成樹 。 我們稱這個問題為最小生成樹問題

minimum spanning tree problem


MST Green color edges are the selected edges for MST.

MST綠色邊緣是MST的選定邊緣。

There are two algorithm to solve this problem: Kruskal's Algorithm and Prim's Algorithm. Each of them run in O(E lg V )

有兩種算法可以解決此問題: Kruskal算法Prim算法 。 它們每個都以O(E lg V)運行

Here we are discussing Kruskal's Algorithm...

在這里,我們討論的是Kruskal算法...

克魯斯卡爾算法 (Kruskal's Algorithm)

This Algorithm first makes the forest of each vertex and then sorts the edges according to their weights, and in each step, it adds the minimum weight edge in the tree that connects two distinct vertexes that do not belong to the same tree in the forest.

該算法首先創建每個頂點的森林,然后根據其權重對邊緣進行排序,然后在每個步驟中,在連接兩個不屬于該森林中同一棵樹的不同頂點的樹中添加最小權重邊緣。

It uses a disjoint set data structure to maintain several disjoint sets of elements. Each set contains the vertices in one tree of the current forest.

它使用不連續集數據結構來維護幾個不連續元素集。 每一組包含當前森林的一棵樹中的頂點。

Example: Here we are finding the cost of MST.

示例:在這里我們發現MST的成本。

Program:

程序:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class MST{
static class set{
int parent,rank;
}
//find set which represents vertex i
static int find(set subsets[],int i ){
if(subsets[i].parent==i)
return i;
return find(subsets,subsets[i].parent);
}
//function for adding  edges whose vertex belongs 
//to the different tree ie. UNION
static void UNION(set subsets[],int x,int y){
int xroot=find(subsets,x);
int yroot=find(subsets,y);
if(subsets[xroot].rank>subsets[yroot].rank)
subsets[yroot].parent=xroot;
else if(subsets[xroot].rank<subsets[yroot].rank)
subsets[xroot].parent=yroot;
else{
subsets[yroot].parent=xroot;
subsets[xroot].rank++;
}
}
static int mst(int n, Integer[][] edges) {
set subsets[]=new set[n];
//Create forest of vrtices that is separate tree for each vertex
for(int i=0;i<n;i++)   
{  
subsets[i]=new set();
subsets[i].parent=i;  // Each vertex is its own parent
subsets[i].rank=0;   //Having no child
}
int e=0,i=0,count=0;
//Create graph having exactly vertex-1 ie. n-1 edges
while(e<n-1){
//find set from which current vertex belongs
int x=find(subsets,edges[i][0]-1);  
//find set from which current vertex belongs
int y=find(subsets,edges[i][1]-1); 
if(x!=y){
count+=edges[i][2];  
e++;
// union the two vertex in the same tree 
//if they belong to the different set
UNION(subsets,x,y); 
}
i++;
}
return count;
}
public static void main(String[] args) 
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();   //number of nodes
int m = in.nextInt();  //number of edges
Integer [][]edges = new Integer[m][3];
for(int edges_i = 0; edges_i < m; edges_i++){
for(int edges_j = 0; edges_j < 3; edges_j++){
edges[edges_i][edges_j] = in.nextInt();
}
}
//Sort edges two dimensional array according to 
//its third column i.e. weight
Arrays.sort(edges,new Comparator<Integer[]>(){
@Override
public int compare(Integer[] i1,Integer[] i2){
//Comparing third column having index 2
return i1[2].compareTo(i2[2]);   
}
});
int result=mst(n,edges);
System.out.println(result);
in.close();
}
}

Output

輸出量

minimum spanning tree problem output

翻譯自: https://www.includehelp.com/java/minimum-spanning-tree-problem-using-kruskals-algorithm.aspx

最小生成樹 kruskal

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/542724.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/542724.shtml
英文地址,請注明出處:http://en.pswp.cn/news/542724.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

mysql數據庫面試題 軟件測試_軟件測試數據庫面試題一

前提本次分享只局限于 sql server 和 mysql 這兩種數據庫&#xff0c;其他數據庫暫不總結正文1. 對查詢的字段進行去重(distinct)用法注意&#xff1a;1. distinct【查詢字段】&#xff0c;必須放在要查詢字段的開頭&#xff0c;即放在第一個參數&#xff1b;2. 只能在SELECT 語…

python數碼時鐘代碼_python時鐘的實現

from time importsleepimporttimeimportosclassClock(object):"""數字時鐘""" def __init__(self, hour0, minute0, second0):"""初始化方法 :param hour: 時 :param minute: 分 :param second: 秒"""self._hourh…

PHP頁面跳轉

本文轉載自&#xff1a;http://blog.sina.com.cn/s/blog_9a06890901014ol1.html PHP頁面跳轉一、header()函數 header函數中Location類型的標頭是一種特殊的header調用&#xff0c;常用來實現頁面跳轉 注意&#xff1a;1、location和“:”號間不能有空格&#xff0c;否則不會跳…

如何打印出給定尺寸的方格_打印給定號碼的表格| 8086微處理器

如何打印出給定尺寸的方格Problem statement: 問題陳述&#xff1a; Write an assembly language program in 8086 to print the table of a given integer. 在8086中編寫匯編語言程序以打印給定整數的表。 Assumptions: Suppose the inputted number is at memory location …

python自動更新excel數據_如何更新Excel數據?(刷新所有查詢)

我有一個帶有一些查詢的Excel xlsm文件。目前我每天打開它&#xff0c;點擊“數據”選項卡中的“全部刷新”命令。我希望這件事能自動完成。我用python編寫了一個腳本(我是python新手)。問題是&#xff0c;刷新數據并保存Excel文件后&#xff0c;刷新的數據不可見(我知道刷新工…

mongoDB 使用手冊

2019獨角獸企業重金招聘Python工程師標準>>> 1、基本操作db.AddUser(username,password) 添加用戶db.auth(usrename,password) 設置數據庫連接驗證db.cloneDataBase(fromhost) 從目標服務器克隆一個數據庫db.commandHelp(name) returns the help for the commanddb.…

android搜索框功能實現_巧用 Trie 樹,實現搜索引擎關鍵詞提示功能

來源 | 碼海責編 | Carol封圖 | CSDN 付費下載于視覺中國我們幾乎每天都在用搜索引擎搜索信息&#xff0c;相信大家肯定有注意過這樣一個細節:當輸入某個字符的時候&#xff0c;搜索引框底下會出現多個推薦詞&#xff0c;如下&#xff0c;輸入「python」后&#xff0c;底下會出…

Python | 從用戶輸入數據,保存到文件,讀取并打印

Here, we have to input the data from the user, to read the data from user, we use input() method, and then the input data we have to store in the file by using write() method and then by using read() method we can get the data. 在這里&#xff0c;我們必須從…

python語句print type 1234的輸出結果是_Python語句 print(type(1J))的輸出結果是

【填空題】遍歷輸出文件所有行。 fopen("d:\\r2.txt","r") while True: str print(str,end) if not str: break f.close()【單選題】執行下列 Python語句將產生的結果是( ) i1 if (i): print(True) else: print( False)【單選題】Python語句 print(type(1/…

qt5.9.0調試如何查看變量的值_深入了解 Java 調試

Bug(俗稱"八阿哥") 是軟件開發繞不過的一道坎&#xff0c;因此調試便成了每位程序員一項必備的核心技能。調試不僅有助于理解程序的運行流程&#xff0c;還能改進代碼質量&#xff0c;最終提高開發者解決問題的能力以及交付軟件的品質。本文旨在討論 Java 調試關鍵技…

python字符串轉浮點數_Python | 打印不同的值(整數,浮點數,字符串,布爾值)...

python字符串轉浮點數In the given example, we are printing different values like integer, float, string and Boolean using print() method in python. 在給定的示例中&#xff0c;我們使用python中的print()方法打印不同的值&#xff0c;例如整數&#xff0c;浮點數&…

(6) 如何用Apache POI操作Excel文件-----POI-3.10的一個和注解(comment)相關的另外一個bug...

如果POI-3.10往一個工作表&#xff08;sheet&#xff09;里面插入數據的話&#xff0c;需要注意了&#xff0c;其有一個不太被容易發現的bug。 被插入的工作表&#xff08;sheet&#xff09;里面的單元格沒有包含任何的注解&#xff08;comment&#xff09;的時候&#xff0c;插…

mysql下拉刷新加載數據_下拉刷新、加載數據功能

paging nick加載更多getData();varm0,n2;//m:button點擊次數 n:一次加載幾條數據$(.page-btn-nick).click(getData);functiongetData(){$.ajax(paging.html).then(function(response){//測試url寫本頁面varobj{developer:[{name:nick},{name:ljy},{name:xzl},{name:jeson},{nam…

mcq 隊列_人工智能邏輯才能問答(MCQ)

mcq 隊列1) Why do we want to implement the concept of Logic in an AI system? So that the agent can have decision making capabilitySo that the agent can think and act humanlySo that the agent can apply the logic for finding the solution to any particular p…

第三周作業!

1、列出當前系統上所有已經登錄的用戶的用戶名&#xff0c;注意&#xff1a;同一個用戶登錄多次&#xff0c;則只顯示一次即可。答&#xff1a;本題思路&#xff1a;先用who命令列出當前登陸的用戶信息&#xff0c;然后使用cut命令對字段進行分割&#xff0c;選出我們需要的字段…

python導入模塊以及類_python模塊的導入以及模塊簡介

標簽&#xff1a; 一、模塊的定義及類型 1、定義 模塊就是用一堆的代碼實現了一些功能的代碼的集合&#xff0c;通常一個或者多個函數寫在一個.py文件里&#xff0c;而如果有些功能實現起來很復雜&#xff0c;那么就需要創建n個.py文件&#xff0c;這n個.py文件的集合就是模塊 …

mysql 指定數字排序_Mysql數據排序

排序數據普通字段排序按照單一字段排序按照多個字段排序手動指定排序順序單個字段手動排序多個字段手動排序普通字段排序按照單一字段排序排序采用order by子句&#xff0c;order by后面跟上排序字段&#xff0c;排序字段可以放多個&#xff0c;多個采用逗號間隔&#xff0c;or…

《黃帝內經 —— 央視60集紀錄片》

下載地址&#xff1a; http://pan.baidu.com/s/1dFI8hxf 目錄 第一部 醫史篇第1集&#xff1a;神奇的秘笈&#xff08;《黃帝內經》是部什么書&#xff09;第2集&#xff1a;赫赫始祖&#xff08;上&#xff09;&#xff08;黃帝、炎帝&#xff09;第3集&#xff1a;赫赫始祖&a…

mnist手寫數字數據集_mnist手寫數據集(1. 加載與可視化)

》》歡迎 點贊&#xff0c;留言&#xff0c;收藏加關注《《1. 模型構建的步驟&#xff1a;在構建AI模型時&#xff0c;一般有以下主要步驟&#xff1a;準備數據、數據預處理、劃分數據集、配置模型、訓練模型、評估優化、模型應用&#xff0c;如下圖所示&#xff1a;【注意】由…

python凱撒密碼實現_密碼:凱撒密碼及其Python實現

python凱撒密碼實現Before we start let’s some basic terminology... 在開始之前&#xff0c;讓我們先介紹一些基本術語... The art and science to achieve security by encoding messages to make them unreadable are known as Cryptography. That’s what the whole art…