๊ทธ๋ํ๊ฐ ์ฃผ์ด์ก์ ๋, ๊ทธ ๊ทธ๋ํ์ ์ต์ ์คํจ๋ ํธ๋ฆฌ๋ฅผ ๊ตฌํ๋ ํ๋ก๊ทธ๋จ์ ์์ฑํ์์ค.
์ต์ ์คํจ๋ ํธ๋ฆฌ๋, ์ฃผ์ด์ง ๊ทธ๋ํ์ ๋ชจ๋ ์ ์ ๋ค์ ์ฐ๊ฒฐํ๋ ๋ถ๋ถ ๊ทธ๋ํ ์ค์์ ๊ทธ ๊ฐ์ค์น์ ํฉ์ด ์ต์์ธ ํธ๋ฆฌ๋ฅผ ๋งํ๋ค.
์ ๋ ฅ
์ฒซ์งธ ์ค์ ์ ์ ์ ๊ฐ์ V(1 โค V โค 10,000)์ ๊ฐ์ ์ ๊ฐ์ E(1 โค E โค 100,000)๊ฐ ์ฃผ์ด์ง๋ค. ๋ค์ E๊ฐ์ ์ค์๋ ๊ฐ ๊ฐ์ ์ ๋ํ ์ ๋ณด๋ฅผ ๋ํ๋ด๋ ์ธ ์ ์ A, B, C๊ฐ ์ฃผ์ด์ง๋ค. ์ด๋ A๋ฒ ์ ์ ๊ณผ B๋ฒ ์ ์ ์ด ๊ฐ์ค์น C์ธ ๊ฐ์ ์ผ๋ก ์ฐ๊ฒฐ๋์ด ์๋ค๋ ์๋ฏธ์ด๋ค. C๋ ์์์ผ ์๋ ์์ผ๋ฉฐ, ์ ๋๊ฐ์ด 1,000,000์ ๋์ง ์๋๋ค.
๊ทธ๋ํ์ ์ ์ ์ 1๋ฒ๋ถํฐ V๋ฒ๊น์ง ๋ฒํธ๊ฐ ๋งค๊ฒจ์ ธ ์๊ณ , ์์์ ๋ ์ ์ ์ฌ์ด์ ๊ฒฝ๋ก๊ฐ ์๋ค. ์ต์ ์คํจ๋ ํธ๋ฆฌ์ ๊ฐ์ค์น๊ฐ -2,147,483,648๋ณด๋ค ํฌ๊ฑฐ๋ ๊ฐ๊ณ , 2,147,483,647๋ณด๋ค ์๊ฑฐ๋ ๊ฐ์ ๋ฐ์ดํฐ๋ง ์ ๋ ฅ์ผ๋ก ์ฃผ์ด์ง๋ค.
์ถ๋ ฅ
์ฒซ์งธ ์ค์ ์ต์ ์คํจ๋ ํธ๋ฆฌ์ ๊ฐ์ค์น๋ฅผ ์ถ๋ ฅํ๋ค.
Kruskal Algorithm ์ด์ฉ
๐ก PriorityQueue ์ด์ฉํ์ฌ ๊ฐ์ฅ ์์ ๊ฐ์ค์น๋ถํฐ ์ฐ๊ฒฐํจ
๐ก ์ฌ์ดํด์ ์๊ธฐ์ง ์๊ฒ ํ๋ ค๊ณ , Union & Find ์ด์ฉํ์ฌ Disjoint set ๊ตฌํ
1) PriorityQueue ์ด์ฉํ์ฌ ๊ฐ์ฅ ์์ ๊ฐ์ค์น๋ถํฐ ์ฐ๊ฒฐํจ
pq.offer(new Edge(start,end,cost));
...
while(!pq.isEmpty()) {
Edge e = pq.poll();
if(find(e.start) == find(e.end))
continue;
else {
union(e.start, e.end);
count+=e.cost;
}
}
2) findํจ์๋ฅผ ํตํด ์๋ก์ root๊ฐ ๊ฐ์์ง ํ์ธ(์ฌ์ดํด ์์ ๊ธฐ ์ํด)
static int find(int e) {
if(parent[e] == e) return e;
return parent[e] = find(parent[e]);
}
3) unionํจ์๋ฅผ ํตํด ์๋ก๋ฅผ ํธ๋ฆฌ๋ก ์ฐ๊ฒฐํจ
static void union(int a, int b) {
int rootA = find(a);
int rootB = find(b);
if(rootA != rootB)
parent[rootB] = rootA;
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.PriorityQueue;
public class MST_1 {
static int[] parent;
static PriorityQueue<Edge> pq;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s[] = br.readLine().split(" ");
int count = 0;
int V = Integer.parseInt(s[0]);
int E = Integer.parseInt(s[1]);
parent = new int[V+1];
pq = new PriorityQueue<Edge>();
for(int i=0; i<V+1; i++)
parent[i] = i;
for(int i=0; i<E; i++) {
s = br.readLine().split(" ");
int start = Integer.parseInt(s[0]);
int end = Integer.parseInt(s[1]);
int cost = Integer.parseInt(s[2]);
pq.offer(new Edge(start,end,cost));
}
while(!pq.isEmpty()) {
Edge e = pq.poll();
if(find(e.start) == find(e.end)) continue;
else {
union(e.start, e.end);
count+=e.cost;
}
}
System.out.println(count);
}
static int find(int e) {
if(parent[e] == e) return e;
return parent[e] = find(parent[e]);
}
static void union(int a, int b) {
int rootA = find(a);
int rootB = find(b);
if(rootA != rootB) parent[rootB] = rootA;
}
static class Edge implements Comparable<Edge>{
int start;
int end;
int cost;
Edge(int start, int end, int cost){
this.start = start;
this.end = end;
this.cost = cost;
}
@Override
public int compareTo(Edge o) {
return this.cost - o.cost;
}
}
}
์ฑ๊ณตโจ