[JAVA-자바] 1967번: 트리의 지름

2025. 5. 3. 17:35·알고리즘/백준

 

소스코드:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;

public class Main {

    public static class Node {
        int to;
        int cost;

        Node(int t, int c) {
            this.to = t;
            this.cost = c;
        }
    }

    static BufferedReader br;
    static BufferedWriter bw;
    static int N;
    static ArrayList<List<Node>> treeList;
    static int maxLength;
    static int farNode;
    static boolean[] visited;

    public static void main(String[] args) throws IOException {
        br = new BufferedReader(new InputStreamReader(System.in));
        bw = new BufferedWriter(new OutputStreamWriter(System.out));

        N = Integer.parseInt(br.readLine());
        treeList = new ArrayList<>();
        for (int i = 0; i <= N; i++) {
            treeList.add(new ArrayList<>());
        }

        for (int i = 1; i < N; i++) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            int idx = Integer.parseInt(st.nextToken());
            int to = Integer.parseInt(st.nextToken());
            int cost = Integer.parseInt(st.nextToken());
            treeList.get(idx).add(new Node(to, cost));
            treeList.get(to).add(new Node(idx, cost));
        }
        br.close();

        maxLength = 0;
        farNode = 0;
        visited = new boolean[N + 1];
        dfs(1, 0);

        Arrays.fill(visited, false);
        dfs(farNode, 0);

        bw.write(maxLength + "\n");
        bw.close();
    }

    public static void dfs(int start, int sum) {
        visited[start] = true;

        if (sum > maxLength) {
            maxLength = sum;
            farNode = start;
        }

        for (Node nextNode : treeList.get(start)) {
            if (!visited[nextNode.to]) {
                dfs(nextNode.to, sum + nextNode.cost);
            }
        }
    }
}

 

글의 내용 중 잘못된 점이나 수정이 필요한 부분, 혹은 궁금한 사항이 있다면 언제든 댓글로 남겨주시면 감사하겠습니다.

여러분의 피드백은 더 나은 글을 작성하는 데 큰 도움이 됩니다. 감사합니다.

'알고리즘 > 백준' 카테고리의 다른 글

[JAVA-자바] 2448번: 별 찍기 - 11  (0) 2025.05.05
[JAVA-자바] 1987번: 알파벳  (0) 2025.05.03
[JAVA-자바] 1753번: 최단경로  (0) 2025.05.02
[JAVA-자바] 1504번: 특정한 최단 경로  (0) 2025.05.02
[JAVA-자바] 1043번: 거짓말  (0) 2025.04.30
'알고리즘/백준' 카테고리의 다른 글
  • [JAVA-자바] 2448번: 별 찍기 - 11
  • [JAVA-자바] 1987번: 알파벳
  • [JAVA-자바] 1753번: 최단경로
  • [JAVA-자바] 1504번: 특정한 최단 경로
raven
raven
Github : https://github.com/RabeMaster | Email : ra___be@naver.com
  • raven
    배움을 원하는 사람
    raven
  • 전체
    오늘
    어제
  • 공지사항

    • 안녕하세요
    • 분류 전체보기 (169)
      • 네이버 부스트캠프 10기 (7)
        • 멤버십 (5)
        • 챌린지 (1)
        • 베이직 (1)
      • 공부 (2)
        • JAVA (1)
        • CS (0)
        • 정보처리기사 (1)
      • 알고리즘 (159)
        • 백준 (159)
      • 개발 (1)
        • 백준 확장 프로그램 (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 인기 글

  • 태그

    문자열
    코딩테스트
    정렬
    코딩
    네이버
    수학
    자바
    백준
    멤버십
    브루트포스 알고리즘
    백트래킹
    부스트캠프
    자료 구조
    스택
    그래프 탐색
    다이나믹 프로그래밍
    최단 경로
    그래프 이론
    java
    네이버부스트캠프
    구현
    IT
    회고
    네부캠
    너비 우선 탐색
    알고리즘
    개발
    코테
    부트캠프
    그리디 알고리즘
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.1
raven
[JAVA-자바] 1967번: 트리의 지름
상단으로

티스토리툴바