給定一個n個點m條邊的無向圖,圖中可能存在重邊和自環,邊權可能為負數,
求最小生成樹的樹邊權重之和,如果最小生成樹不存在則輸出impossible,
給定一張邊帶權的無向圖G=(V, E),其中V表示圖中點的集合,E表示圖中邊的集合,n=|V|,m=|E|,
由V中的全部n個頂點和E中n-1條邊構成的無向連通子圖被稱為G的一棵生成樹,其中邊的權值之和最小的生成樹被稱為無向圖G的最小生成樹,
輸入格式
第一行包含兩個整數n和m,
接下來m行,每行包含三個整數u,v,w,表示點u和點v之間存在一條權值為w的邊,
輸出格式
共一行,若存在最小生成樹,則輸出一個整數,表示最小生成樹的樹邊權重之和,如果最小生成樹不存在則輸出impossible,
資料范圍
1≤n≤1051≤n≤105,
1≤m≤2?1051≤m≤2?105,
圖中涉及邊的邊權的絕對值均不超過1000,
輸入樣例:
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); } }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/95243.html
標籤:其他
