알고리즘
Union-Find
by 출근길
2018. 7. 17.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
class Edge implements Comparable, Comparator {
int s;
int e;
int w;
Edge(int s, int e, int w) {
this.s = s;
this.e = e;
this.w = w;
}
@Override
public int compare(Edge arg0, Edge arg1) {
if (arg0.w < arg1.w) {
return -1;
} else if (arg0.w > arg1.w) {
return 1;
}
return 0;
}
@Override
public int compareTo(Edge arg0) {
if (this.w < arg0.w) {l
return -1;
} else if (this.w > arg0.w) {
return 1;
}
return 0;
}
}
public class Main {
/*
* 최소 스패닝 트리 https://vwww.acmicpc.net/problem/11758
*/
static int[] P;
public static void main(String[] args) throws IOException {
//System.setIn(new FileInputStream("res/algo4/F.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer ST = new StringTokenizer(br.readLine());
int V = Integer.parseInt(ST.nextToken());
int E = Integer.parseInt(ST.nextToken());
ArrayList A = new ArrayList();
int a = 0, b = 0, w = 0;
for (int i = 1; i <= E; i++) {
ST = new StringTokenizer(br.readLine());
a = Integer.parseInt(ST.nextToken());
b = Integer.parseInt(ST.nextToken());
w = Integer.parseInt(ST.nextToken());
A.add(new Edge(a, b, w));
}
// priority 큐 입력
PriorityQueue pq = new PriorityQueue();
for (int i = 0; i < E; i++) {
pq.add(A.get(i));
}
P = new int[V + 1];
for (int i = 1; i <= V; i++){
P[i] = i;
}
int result = 0;
for (int i = 0; i < E; i++){
Edge node = pq.poll();
int s = node.s;
int e = node.e;
int ps = find(s);
int pe = find(e);
if (ps != pe) {
union(s, e);
result += node.w;
}
}
bw.write(result+"\n");
br.close();
bw.flush();
bw.close();
}
static void union(int a, int b) {
int ua = find(a);
int ub = find(b);
if (ua == ub) return;
P[ua] = b;
}
static int find(int a) {
if (P[a] == a) return a;
return P[a] = find(P[a]);
}
}