生活随笔
收集整理的這篇文章主要介紹了
还是畅通工程(克鲁斯卡尔算法+并查集)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
還是暢通工程
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 53997 Accepted Submission(s): 24504
Problem Description
某省調查鄉村交通狀況,得到的統計表中列出了任意兩村莊間的距離。省政府“暢通工程”的目標是使全省任何兩個村莊間都可以實現公路交通(但不一定有直接的公路相連,只要能間接通過公路可達即可),并要求鋪設的公路總長度為最小。請計算最小的公路總長度。
Input
測試輸入包含若干測試用例。每個測試用例的第1行給出村莊數目N ( < 100 );隨后的N(N-1)/2行對應村莊間的距離,每行給出一對正整數,分別是兩個村莊的編號,以及此兩村莊間的距離。為簡單起見,村莊從1到N編號。
當N為0時,輸入結束,該用例不被處理。
Output
對每個測試用例,在1行里輸出最小的公路總長度。
Sample Input
3
1 2 1
1 3 2
2 3 4
4
1 2 1
1 3 4
1 4 1
2 3 3
2 4 2
3 4 5
0
Sample Output
3
5
Hint
Hint
Huge input, scanf is recommended.
Source
浙大計算機研究生復試上機考試-2006年
Recommend
JGShining
克魯斯卡爾算法,并查集的靈活運行。
解題步驟:
1、初始化并查集用的數組 father[i]=i
2、輸入連接的起始點,并按照權值排序,排序重寫了set中的比較器中的方法
3、由于List集合可以根據索引獲取對象,為了方便把set集合轉換成ArrayList,然后可以調用get方法獲取對象的值,接著遍歷這N*(N-1)個路徑并get起點和終點判斷其祖先是否相同,也就是兩個點是否連通,如果不連通,那么更新father數組值,并加上這兩點的權值,輸出最終結果
package com.test;import java.util.ArrayList;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;class Node implements Comparable<Node>{
public int from;
public int to;
public int value;
public Node(
int from,
int to,
int value){
this.
from=
from;
this.to=to;
this.
value=
value;}@Override
public int compareTo(Node o) {
if(
this.
value>o.
value)
return 1;
return -
1;}
}
public class Main {
public static void main(String[] args) {
int N;Scanner sc =
new Scanner(System.
in);
while(sc.hasNext()){N=sc.nextInt();ArrayList<Node> list =
new ArrayList<>();Set<Node>
set =
new TreeSet<>();
int[] father=
new int[N+
1];
for (
int i =
0; i < N; i++) {father[i]=i;}
for (
int i =
0; i < N*(N-
1)/
2; i++) {
int a,b,c;a=sc.nextInt();b=sc.nextInt();c=sc.nextInt();list.add(
new Node(a, b, c));}
set.addAll(list);list.clear();;list.addAll(
set);
int sum=
0;
for(
int i=
0;i<N*(N-
1)/
2;i++){
if(Find(father,list.
get(i).
from)!=Find(father,list.
get(i).to)){
int a=Find(father,list.
get(i).
from);
int b=Find(father,list.
get(i).to);father[a]=b;sum+=list.
get(i).
value;}}System.
out.println(sum);}}
private static int Find(
int[] father,
int from) {
if(
from!=father[
from]){father[
from]=Find(father,father[
from]);}
return father[
from];}}
總結
以上是生活随笔為你收集整理的还是畅通工程(克鲁斯卡尔算法+并查集)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。