859. Kruskal算法求最小生成樹(模板)

給定一個n個點m條邊的無向圖,圖中可能存在重邊和自環,邊權可能爲負數。java

求最小生成樹的樹邊權重之和,若是最小生成樹不存在則輸出impossible。node

給定一張邊帶權的無向圖G=(V, E),其中V表示圖中點的集合,E表示圖中邊的集合,n=|V|,m=|E|。ide

由V中的所有n個頂點和E中n-1條邊構成的無向連通子圖被稱爲G的一棵生成樹,其中邊的權值之和最小的生成樹被稱爲無向圖G的最小生成樹。this

輸入格式

第一行包含兩個整數n和m。spa

接下來m行,每行包含三個整數u,v,w,表示點u和點v之間存在一條權值爲w的邊。code

輸出格式

共一行,若存在最小生成樹,則輸出一個整數,表示最小生成樹的樹邊權重之和,若是最小生成樹不存在則輸出impossible。xml

數據範圍

1n1051≤n≤105,
1m21051≤m≤2∗105,
圖中涉及邊的邊權的絕對值均不超過1000。
blog

輸入樣例:

4 5
1 2 1
1 3 2
1 4 3
2 3 2
3 4 4

輸出樣例:


代碼:6
//思路:先把全部邊按照權值從小到大排序
//枚舉每條邊a,b和權重w,
//若是a,b不連通,則將這條邊加入到集合中

import java.util.Arrays;
import java.util.Scanner;

class Node implements Comparable<Node>{
      int a;
      int b;
      int w;
      public Node(int a,int b,int w){
              this.a=a;
              this.b=b;
              this.w=w;
      }
      @Override
      public int compareTo(Node o) {
          return this.w-o.w;
      }
}
 public class Main{
         static final int N=100005;
         static int p[]=new int[N];
         static Node node[]=new Node[2*N];
         static int n,m;
         static int find(int x){
                 if(p[x]!=x) p[x]=find(p[x]);
                 return p[x];
         }
         public static void main(String[] args) {
                 Scanner scan=new Scanner(System.in);
                 n=scan.nextInt();
                 m=scan.nextInt();
                 for(int i=0;i<m;i++){
                         int a=scan.nextInt();
                         int b=scan.nextInt();
                         int w=scan.nextInt();
                         node[i]=new Node(a,b,w);
                 }
                 Arrays.sort(node,0,m);
                 for(int i=1;i<=n;i++) p[i]=i;
                 int res=0,cnt=0;
                 for(int i=0;i<m;i++){
                         int a=node[i].a;
                         int b=node[i].b;
                         if(find(a)!=find(b)){
                                 res+=node[i].w;
                                 cnt++;
                                 p[find(a)]=b;
                         }
                 }
                 //n個點由n-1條邊連着
                 if(cnt!=n-1) System.out.println("impossible");
                 else System.out.println(res);
        }
 }
相關文章
相關標籤/搜索