문제
풀이
전형적인 크루스칼 알고리즘 풀이다.
1. Edge의 weight크기가 작은 순으로 정렬
2. Edge를 집합에 포함 시키기위해 find(x) 함수를 호출해서 parent가 같은지 확인
3. Parent가 같지 않은 Edge 한에서 Union을 호출하여 집합에 포함시킨 후 가중치 합을 반환
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
|
import java.util.*;
import java.io.*;
class Solution{
static int[] parent;
static ArrayList<Edge> list = new ArrayList<Edge>();
static int answer=0;
public int solution(int n,int[][] costs){
parent = new int[n+1];
for (int i=1;i<=n;i++)
parent[i]=i;
Arrays.stream(costs).map(e->new Edge(e[0],e[1],e[2]))
.forEach(edge -> list.add(edge));
Collections.sort(list);
list.stream().filter(edge->find(edge.start) != find(edge.end))
.forEach(edge -> union(edge.start, edge.end, edge.weight));
return answer;
}
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 weight){
if(find(x)!=find(y))
parent[find(x)] = y;
answer+=weight;
}
}
class Edge implements Comparable<Edge>{
int weight;
int start;
int end;
public Edge(int start,int end, int weight)
{
this.start=start;
this.end=end;
this.weight=weight;
}
@Override
public int compareTo(Edge o) {
// TODO Auto-generated method stub
return this.weight-o.weight;
}
}
|
cs |
'알고리즘,PS > 프로그래머스' 카테고리의 다른 글
[프로그래머스] [Level2] 소수찾기 JAVA (0) | 2021.10.20 |
---|---|
[프로그래머스] [위클리 챌린지 11주차] 아이템줍기 JAVA (2) | 2021.10.19 |
[BOJ] 백준 [9466] 텀 프로젝트 JAVA (0) | 2021.10.17 |
[프로그래머스] [level3] 디스크 컨트롤러 JAVA (0) | 2021.10.11 |
[프로그래머스] [위클리 챌린지 9주차] 전력망을 둘로 나누기 JAVA (0) | 2021.10.05 |