본문 바로가기
Problem Solving/Baekjoon

[백준] 6018 Tea Time - Graph Theory / Java

by graycode 2024. 1. 8.

 문제 링크

 

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;
    }

}

댓글