MST 최소 스패닝트리를 찾는 기본 문제
https://www.acmicpc.net/problem/1922
Kruscal 방식으로 MST를 구함.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class boj1922 {
static int N, M;
static Edge[] edges;
static DJS djs;
static class DJS {
int[] mom;
DJS(int n) {
mom = new int[n+1];
for (int i = 1; i <= n ; i++) mom[i] = i;
}
public int getMom(int n){
if(n==mom[n]) return n;
mom[n] = getMom(mom[n]);
return mom[n];
}
public boolean isSame(int a, int b){
return (getMom(a)==getMom(b));
}
public void union(int a, int b) {
a = getMom(a);
b = getMom(b);
if(a==b) return;
mom[b] = a;
}
}
static class Edge implements Comparable<Edge> {
int s, e, v;
Edge(int s, int e, int v) {
this.s = s;
this.e = e;
this.v = v;
}
@Override
public int compareTo(Edge o) {
return this.v - o.v;
}
}
public static void main(String[] args) throws IOException {
System.setIn(new FileInputStream("res/boj_1922.txt"));
long Start = System.currentTimeMillis();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
M = Integer.parseInt(br.readLine());
edges = new Edge[M];
djs = new DJS(N);
StringTokenizer st;
int a, b, c;
for (int i = 1; i <= M ; i++) {
st = new StringTokenizer(br.readLine(), " ");
a = Integer.parseInt(st.nextToken());
b = Integer.parseInt(st.nextToken());
c = Integer.parseInt(st.nextToken());
edges[i-1] = new Edge(a, b, c);
}
Arrays.sort(edges);
Edge ed;
long result = 0;
for (int i = 0; i < M ; i++) {
ed = edges[i];
if(!djs.isSame(ed.s, ed.e)) {
djs.union(ed.s,ed.e);
result += ed.v;
}
}
System.out.println(result);
}
}