858. Prim算法求最小生成樹(模板)

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

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

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

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

輸入格式

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

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

輸出格式

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

數據範圍

1n5001≤n≤500,
1m1051≤m≤105,
圖中涉及邊的邊權的絕對值均不超過10000。
im

輸入樣例:

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);
        }
 }
相關文章
相關標籤/搜索