• 문제 링크
6018번: Tea Time
N (1 <= N <= 1000) cows, conveniently numbered 1..N all attend a tea time every day. M (1 <= M <= 2,000) unique pairs of those cows have already met before the first tea time. Pair i of these cows who have met is specified by two differing integers A_i and
www.acmicpc.net
• 풀이 코드
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class Main {
static int[] parent;
public static void main(String[] args) throws IOException {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringBuilder sb = new StringBuilder();
int n = read(), m = read(), q = read();
parent = new int[n + 1];
for (int i = 1; i <= n; i++) parent[i] = i;
while (m-- > 0) union(read(), read());
while (q-- > 0) sb.append(find(read()) == find(read()) ? "Y\n" : "N\n");
bw.write(sb.toString());
bw.flush();
}
private static void union(int a, int b) {
a = find(a);
b = find(b);
if (a != b) parent[b] = a;
}
private static int find(int node) {
if (node == parent[node]) return node;
return parent[node] = find(parent[node]);
}
private static int read() throws IOException {
int c, n = System.in.read() & 15;
while ((c = System.in.read()) > 32) n = (n << 3) + (n << 1) + (c & 15);
return n;
}
}
'Problem Solving > Baekjoon' 카테고리의 다른 글
[백준] 5991 Papaya Jungle - Graph Theory / Java (0) | 2024.01.10 |
---|---|
[백준] 26999 Satellite Photographs - Graph Theory / Java (0) | 2024.01.09 |
[백준] 6188 Clear Cold Water - Graph Theory / Java (0) | 2024.01.07 |
[백준] 9255 The Friend of My Enemy is My Enemy - Graph Theory / Java (0) | 2024.01.06 |
[백준] 6601 Knight Moves - Graph Theory / Java (0) | 2024.01.05 |
댓글