https://www.acmicpc.net/problem/1197
1197번: 최소 스패닝 트리
첫째 줄에 정점의 개수 V(1 ≤ V ≤ 10,000)와 간선의 개수 E(1 ≤ E ≤ 100,000)가 주어진다. 다음 E개의 줄에는 각 간선에 대한 정보를 나타내는 세 정수 A, B, C가 주어진다. 이는 A번 정점과 B번 정점이
www.acmicpc.net
문제
풀이
크루스칼 알고리즘을 이용한 최소 신장트리를 구하는 문제이다.
Edge를 weight가 작은 순으로 Queue에 넣은 뒤 ( priorityQueue사용)
parent 배열의 크기를 정점의 갯수만큼 정해주고 ,
union연산으로 disjointSet을 만들어가면서 가중치를 더하는 식으로 하면 된다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
import java.util.*;
import java.io.*;
public class Main{
static int V,E,sum;
static int[] parent;
static PriorityQueue<Edge> pq = new PriorityQueue<Edge>();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] input = br.readLine().split(" ");
V = Integer.parseInt(input[0]); E = Integer.parseInt(input[1]);
for(int i=0;i<E;i++){
input = br.readLine().split(" ");
int start = Integer.parseInt(input[0]);
int end = Integer.parseInt(input[1]);
int weight = Integer.parseInt(input[2]);
pq.add(new Edge(start,end,weight));
}
parent = new int[V+1];
for(int i=1;i<=V;i++)
parent[i] = i;
while(!pq.isEmpty()){
Edge poll = pq.poll();
int s = poll.start;
int e = poll.end;
int w = poll.weight;
if(find(s)==find(e))
continue;
union(s,e);
sum+=w;
}
System.out.println(sum);
}
static int find(int x){
if(x == parent[x])
return x;
parent[x] = find(parent[x]);
return parent[x];
}
static void union(int x,int y){
int xRoot = find(x);
int yRoot = find(y);
if(xRoot != yRoot)
parent[yRoot] = x;
}
static class Edge implements Comparable<Edge>{
int start,end;
int weight;
public Edge(int start, int end, int weight) {
this.start = start;
this.end = end;
this.weight = weight;
}
@Override
public int compareTo(Edge o) {
return this.weight-o.weight;
}
}
}
|
cs |
'알고리즘,PS > 백준' 카테고리의 다른 글
[BOJ] 백준 [1946] 신입사원 JAVA (0) | 2021.09.13 |
---|---|
[BOJ] 백준 [2252] 줄 세우기 JAVA (0) | 2021.09.09 |
[BOJ] 백준 [1806] 부분합 JAVA (0) | 2021.09.08 |
[BOJ] 백준 [3273] 두 수의 합 JAVA (0) | 2021.09.08 |
[BOJ] 백준 [1654] 랜선 자르기 JAVA (0) | 2021.09.06 |