給定一個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≤5001≤n≤500,
1≤m≤1051≤m≤105,
圖中涉及邊的邊權的絕對值均不超過10000,
輸入樣例:
4 5
1 2 1
1 3 2
1 4 3
2 3 2
3 4 4
輸出樣例:
6
加點
代碼:
import java.util.Arrays; //存在負邊,不存在負權回路 //思想:每次加到點集距離最近的點,然后更新其他點到這個點集的距離 //因為n=500,采用鄰接矩陣存盤 import java.util.Scanner; public class Main{ static final int N=505, INF=0x3f3f3f3f; static int n,m; static int g[][]=new int[N][N]; static boolean vis[]=new boolean[N]; static int dis[]=new int[N]; static int res=0; static int prim(){ Arrays.fill(dis, INF); for(int i=0;i<n;i++){ int t=-1; for(int j=1;j<=n;j++) if(!vis[j] && (t==-1 || dis[t]>dis[j])) t=j; if(i!=0 && dis[t]==INF) return INF;//圖不連通 if(i!=0) res+=dis[t];//先加上,后邊再更新;否則,dis[t]可能被更新,因為自環 vis[t]=true; for(int j=1;j<=n;j++) dis[j]=Math.min(dis[j], g[t][j]); } return res; } public static void main(String[] args) { Scanner scan=new Scanner(System.in); n=scan.nextInt(); m=scan.nextInt(); for(int i=1;i<=n;i++) Arrays.fill(g[i], INF); while(m-->0){ int a=scan.nextInt(); int b=scan.nextInt(); int w=scan.nextInt(); g[a][b]=g[b][a]=Math.min(g[a][b],w);//無向邊 有重邊 } int t=prim(); if(t==INF) System.out.println("impossible"); else System.out.println(res); } }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/95242.html
標籤:其他
