[코테 스터디 31일차 TIL] Clear Cold Water

dev_jubby·2024년 8월 21일
0

코테스터디

목록 보기
31/36



💛 오늘의 학습 키워드

[DFS/BFS] Clear Cold Water



📝 문제

문제 설명

The steamy, sweltering summers of Wisconsin's dairy district stimulate the cows to slake their thirst. Farmer John pipes clear cold water into a set of N (3 <= N <= 99999; N odd) branching pipes conveniently numbered 1..N from a pump located at the barn. As the water flows through the pipes, the summer heat warms it. Bessie wants to find the coldest water so she can enjoy the weather more than any other cow.

She has mapped the entire set of branching pipes and noted that they form a tree with its root at the farm and furthermore that every branch point has exactly two pipes exiting from it. Surprisingly, every pipe is exactly one unit in length; of course, all N pipes connect up in one way or another to the pipe-tree.

Given the map of all the pipe connections, make a list of the distance from the barn for every branching point and endpoint. Bessie will use the list to find the very coldest water.

The endpoint of a pipe, which might enter a branching point or might be a spigot, is named by the pipe's number. The map contains C (1 <= C <= N) connections, each of which specifies three integers: the endpoint E_i (1 <= E_i <= N) of a pipe and two branching pipes B1_i and B2_i (2 <= B1_i <= N; 2 <= B2_i <= N). Pipe number 1 connects to the barn; the distance from its endpoint to the barn is 1.

입력

  • Line 1: Two space-separated integers: N and C
  • Lines 2..C+1: Line i+1 describes branching point i with three space-separated integers: E_i, B1_i, and B2_i

출력

  • Lines 1..N: Line i of the output contains a single integer that is the distance from the barn to the endpoint of pipe i

입출력 예

Example 입력

5 2
3 5 4
1 2 3

Example 출력

1
2
2
3
3




💬 내 풀이

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class Main {

    static int[] arr;

    public static void main(String[] args) throws IOException {
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        StringBuilder sb = new StringBuilder();

        int n = read(), c = read();

        arr = new int[n + 1];
        while (c-- > 0) {
            int p = read();
            arr[read()] = p;
            arr[read()] = p;
        }

        for (int i = 1; i <= n; i++) sb.append(dfs(i, 1)).append("\n");

        bw.write(sb.toString());
        bw.flush();
    }

    private static int dfs(int p, int cnt) {
        if (p == 1) return cnt;
        return dfs(arr[p], cnt + 1);
    }

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

}

💻 내 접근 방법

  1. 문제 풀기 실패...재도전



profile
신입 개발자 쥬비의 기술 블로그 입니다.

0개의 댓글