https://mygumi.tistory.com/245
백준 10775번 공항 :: 마이구미
이 글은 백준 알고리즘 문제 10775번 "공항" 을 풀이한다. 문제 풀이는 유니온-파인드(union-find) 또는 디스조인트-셋(disjoint-set) 이라고 불리는 자료구조를 이용한다. 유니온-파인드 이해 - http://mygum
mygumi.tistory.com
https://brenden.tistory.com/33
[알고리즘] 유니온 파인드 (Union-Find)
유니온 파인드(Union-Find) ① 유니온 파인드란? ▷ 대표적 그래프 알고리즘으로 '합집합 찾기'라는 의미를 가지고 있습니다. ▷ 상호 배타적 집합(Disjoint-set)이라고도 합니다. ▷ 여러 노드가 존재
brenden.tistory.com
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static int G,P;
static int[] parent;
static boolean no_add = false;
public static void main(String arg[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
G = Integer.parseInt(br.readLine());
P = Integer.parseInt(br.readLine());
parent = new int[G+1];
int result = 0;
for(int i = 0; i <= G; i++) {
parent[i] = i;
}
for(int i = 0; i < P; i++) {
int temp = Integer.parseInt(br.readLine());
union(temp-1, temp);
if(!no_add)
result++;
}
System.out.println(result);
}
static int find(int x) {
//자기 자신을 바라보면 리턴
if(x == parent[x])
return x;
return parent[x] = find(parent[x]);
}
static int union(int x, int y) {
if(x == -1) {
no_add = true;
return 0;
}
x = find(x); //받은값 - 1
y = find(y); //받은값
if(x == y) {
parent[y] = union(x-1, x);
}
if(x != y) {
parent[y] = x; //받은값의 부모는 받은값 - 1의 부모(자기 자신일 수 있다)
}
return parent[y];
}
}
'백준' 카테고리의 다른 글
[백준] 9465 스티커 [자바] (0) | 2022.06.21 |
---|---|
[백준] 2096 내려가기 [자바] (0) | 2022.06.17 |
[백준] 18352 특정 거리의 도시 찾기 [자바] (0) | 2022.05.26 |
[백준] 1167 트리의 지름 [자바] (0) | 2022.05.23 |
[백준] 25180 썸 팰린드롬 [자바] (0) | 2022.05.18 |