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.
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;
}
}