AcWing 858. Prim Minimum spanning tree(Prim) Described by Java

What is the minimun spanning tree?
A minimum spanning tree (MST) or minimum weight spanning tree is a subset of the edges of a connected, edge-weighted undirected graph that connects all the vertices together, without any cycles and with the minimum possible total edge weight.

Now is the simple MST module.

Similar as the Dijkstra, but this time g[][] is to express the distance from the set.

Problem in AcWing

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;

public class Main {
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static PrintWriter pw = new PrintWriter(System.out);
    static int N = 510, n, m;
    static long g[][] = new long[N][N];
    static long dist[] = new long[N];
    static boolean st[] = new boolean[N];

    public static void main(String[] args) throws IOException {
        String s[] = br.readLine().split(" ");
        n = Integer.parseInt(s[0]);
        m = Integer.parseInt(s[1]);
        Arrays.fill(dist, Integer.MAX_VALUE);
        for (int i = 0; i <= n; i++)
            for (int j = 0; j <= n; j++)
                g[i][j] = Integer.MAX_VALUE;

        for (int i = 0; i < m; i++) {
            s = br.readLine().split(" ");
            int a = Integer.parseInt(s[0]);
            int b = Integer.parseInt(s[1]);
            int c = Integer.parseInt(s[2]);
            g[a][b] = g[b][a] = Math.min(g[a][b], c);
        }

        int t = prim();
        if (t == Integer.MAX_VALUE) pw.println("impossible");
        else pw.println(t);

        pw.flush();
        br.close();
    }

    private static int prim() {
        int res = 0;
        for (int i = 0; i < n; i++) {
            int t = -1;
            for (int j = 1; j <= n; j++)
                if (!st[j] && (t == -1 || dist[t] > dist[j]))
                    t = j;
            if (i != 0 && dist[t] == Integer.MAX_VALUE) return Integer.MAX_VALUE;
            if (i != 0) res += dist[t];
            for (int j = 1; j <= n; j++) dist[j] = Math.min(dist[j], g[t][j]);
            st[t] = true;
        }
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值