티스토리 뷰
이 문제는 최소 스패닝 트리를 구현하는 방법중 크루스칼 알고리즘을 이용하여 구현하면 된다.
크루스칼 알고리즘은 그래프 사이 연결의 최소비용을 찾으면 된다.
간선을 비용순으로 정렬하고,
가장작은 비용이 들어가는 간선을 사이클이 생기지 않는 순서대로 선택하면된다.
간선 사이의 사이클은 union, find 연산을 이용하여 처리한다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
import java.util.Comparator; | |
import java.util.Scanner; | |
/** | |
* 백준, 1197 최소 스패닝 트리 크루스칼 알고리즘 | |
* | |
* @author User | |
* | |
*/ | |
public class Main { | |
static int V; | |
static int E; | |
static int[][] edges; | |
static int[] parent; | |
public static void main(String[] args) { | |
Scanner sc = new Scanner(System.in); | |
V = sc.nextInt(); | |
E = sc.nextInt(); | |
parent = new int[V + 1]; | |
for(int i = 1; i <= V; i++) | |
parent[i] = i; | |
edges = new int[E][3]; | |
for (int i = 0; i < E; i++) { | |
int from = sc.nextInt(); | |
int to = sc.nextInt(); | |
int cost = sc.nextInt(); | |
edges[i][0] = from; | |
edges[i][1] = to; | |
edges[i][2] = cost; | |
} | |
sc.close(); | |
Arrays.sort(edges, new Comparator<int[]>() { | |
@Override | |
public int compare(int[] a, int[] b) { | |
return a[2] >= b[2] ? 1 : -1; | |
} | |
}); | |
int sum = 0; | |
int edgeCount = 0; | |
for (int i = 0; i < E; i++) { | |
int from = edges[i][0]; | |
int to = edges[i][1]; | |
int cost = edges[i][2]; | |
if (find(from) != find(to)) { | |
union(from, to); | |
sum += cost; | |
if (++edgeCount == V - 1) | |
break; | |
} | |
} | |
System.out.println(sum); | |
} | |
public static int find(int x) { | |
if (x == parent[x]) | |
return x; | |
int root = find(parent[x]); | |
parent[x] = root; | |
return root; | |
} | |
public static void union(int x, int y) { | |
x = find(x); | |
y = find(y); | |
parent[y] = x; | |
} | |
} |
반응형
'알고리즘 > 백준' 카테고리의 다른 글
[백준][DP] 11060 점프점프 (0) | 2017.08.23 |
---|---|
[백준] 1005 ACM Craft (0) | 2017.07.20 |
[백준] 1717 집합의 표현(유니온 파인드) (0) | 2017.07.06 |
[백준][그래프] 2623 음악프로그램 (0) | 2017.07.04 |
[백준][위상정렬] 2056 작업 DAG (0) | 2017.06.27 |
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- SPARK
- Tez
- 백준
- AWS
- 파이썬
- 다이나믹
- 알고리즘
- bash
- hbase
- emr
- error
- ubuntu
- 하이브
- java
- airflow
- HIVE
- 오류
- Hadoop
- oozie
- Python
- build
- 하둡
- Linux
- mysql
- nodejs
- SQL
- yarn
- S3
- HDFS
- 정올
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함