문제 원본 : https://www.acmicpc.net/problem/1976
1976번: 여행 가자
동혁이는 친구들과 함께 여행을 가려고 한다. 한국에는 도시가 N개 있고 임의의 두 도시 사이에 길이 있을 수도, 없을 수도 있다. 동혁이의 여행 일정이 주어졌을 때, 이 여행 경로가 가능한 것인
www.acmicpc.net
import java.io.*;
import java.util.StringTokenizer;
public class Main {
static int[] parent;
static int[] depth;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int n = Integer.parseInt(br.readLine());
int m = Integer.parseInt(br.readLine());
parent = new int[n + 1];
depth = new int[n + 1];
for (int i = 1; i <= n; ++i) {
parent[i] = i;
}
StringTokenizer st;
for (int i = 1; i <= n; ++i) {
st = new StringTokenizer(br.readLine());
for (int j = 1; j <= n; ++j) {
if (st.nextToken().equals("1")) {
union(i, j);
}
}
}
st = new StringTokenizer(br.readLine());
int city = Integer.parseInt(st.nextToken());
boolean possible = true;
for (int i = 1; i < m; ++i) {
if (find(city) != find(Integer.parseInt(st.nextToken()))) {
possible = false;
}
}
bw.write(possible ? "YES" : "NO");
bw.close();
br.close();
}
public static int find(int u) {
if (u == parent[u]) {
return u;
}
return parent[u] = find(parent[u]);
}
public static void union(int u, int v) {
u = find(u);
v = find(v);
if (u == v) {
return;
}
if (depth[u] > depth[v]) {
int tmp = u;
u = v;
v = tmp;
}
parent[u] = v;
if (depth[u] == depth[v]) {
++depth[v];
}
}
}
- 유니온-파인드 문제
- 도시가 연결되어 있으면 합쳐주고(union) 여행 계획도시가 전부 연결되어 있는지 체크하면 된다.
'알고리즘 > BOJ' 카테고리의 다른 글
| [BOJ] 4781. 사탕 가게 (0) | 2022.04.08 |
|---|---|
| [BOJ] 5721. 사탕 줍기 대회 (0) | 2022.04.07 |
| [BOJ] 2470. 두 용액 (0) | 2022.04.05 |
| [BOJ] 1715. 카드 정렬하기 (0) | 2022.04.04 |
| [BOJ] 1057. 토너먼트 (0) | 2022.04.03 |