1197번 - 최소 스패닝 트리
2024-07-09
#JAVA#백준
문제 풀이 시간 : 1시간
문제 요약
- •
그래프가 주어졌을 때, 그 그래프의 최소 스패닝 트리를 구하라
- •
정점의 개수 V (1 ≤ V ≤ 10,000)
- •
간선의 개수 E (1 ≤ E ≤ 100,000)
- •
E 개의 줄에 각 간선에 대한 정보 A, B, C 가 주어진다.
- •
A 번과 B 번 정점이 가중치가 C 인 간선으로 연결되었다는 것을 나타낸다.
문제 풀이
이거는 그냥 알고리즘 수업시간때 배웠던 쿠르스칼 알고리즘을 한번 구현해보려고 풀었다.
쿠르스칼은 가중치가 가장 작은 간선을 순서대로 선택하기 때문에 간선의 가중치를 중심으로 먼저 정렬을 해주었다.
Arrays.sort(graph, new Comparator<Node>() {
@Override
public int compare(Node o1, Node o2) {
return o1.c-o2.c;
}
});
그리고 Union - Find 를 활용해서 각 노드가 같은 트리에 있는지 확인하면서
같은 트리에 없다면 해당 간선을 추가해주는 방식으로 진행해주었다.
특히, find 에서 더욱 효율적인 탐색을 위해 새롭게 찾은 부모 노드의 정보를 업데이트 해주어
다음 탐색에서 더 빠르게 찾을 수 있도록 하였따.
public static int find(int a){
if(parent[a]!=a){
parent[a] = find(parent[a]);
}
return parent[a];
}
초기 코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.Provider;
import java.util.*;
public class Main {
public static int V, E;
public static Node[] graph;
public static int[] parent;
public static class Node{
private final int a;
private final int b;
private final int c;
public Node(int a,int b,int c){
this.a = a;
this.b = b;
this.c = c;
}
}
public static int find(int a){
if(parent[a]!=a){
parent[a] = find(parent[a]);
}
return parent[a];
}
public static void union(int a, int b){
int rootA = find(a);
int rootB = find(b);
if(rootA!=rootB){
parent[rootB] = rootA;
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
V = Integer.parseInt(st.nextToken());
E = Integer.parseInt(st.nextToken());
parent = new int[V];
graph = new Node[E];
for(int i=0;i<E;i++){
st = new StringTokenizer(br.readLine());
Node input = new Node(Integer.parseInt(st.nextToken())-1,Integer.parseInt(st.nextToken())-1,Integer.parseInt(st.nextToken()));
graph[i]=input;
}
for(int i=0;i<V;i++){
parent[i]=i;
}
Arrays.sort(graph, new Comparator<Node>() {
@Override
public int compare(Node o1, Node o2) {
return o1.c-o2.c;
}
});
long result = 0L;
for(int i=0;i<E;i++){
Node temp = graph[i];
int p1 = find(temp.a);
int p2 = find(temp.b);
if(p1==p2){
continue;
}
result += temp.c;
union(temp.a, temp.b);
}
System.out.println(result);
}
}