트리의 지름

Huisu·2023년 10월 25일
0

Coding Test Practice

목록 보기
53/98
post-thumbnail

문제

1967번: 트리의 지름

문제 설명

트리(tree)는 사이클이 없는 무방향 그래프이다. 트리에서는 어떤 두 노드를 선택해도 둘 사이에 경로가 항상 하나만 존재하게 된다. 트리에서 어떤 두 노드를 선택해서 양쪽으로 쫙 당길 때, 가장 길게 늘어나는 경우가 있을 것이다. 이럴 때 트리의 모든 노드들은 이 두 노드를 지름의 끝 점으로 하는 원 안에 들어가게 된다.

https://www.acmicpc.net/JudgeOnline/upload/201007/ttrrtrtr.png

이런 두 노드 사이의 경로의 길이를 트리의 지름이라고 한다. 정확히 정의하자면 트리에 존재하는 모든 경로들 중에서 가장 긴 것의 길이를 말한다.

입력으로 루트가 있는 트리를 가중치가 있는 간선들로 줄 때, 트리의 지름을 구해서 출력하는 프로그램을 작성하시오. 아래와 같은 트리가 주어진다면 트리의 지름은 45가 된다.

https://www.acmicpc.net/JudgeOnline/upload/201007/tttttt.png

트리의 노드는 1부터 n까지 번호가 매겨져 있다.

제한 사항

파일의 첫 번째 줄은 노드의 개수 n(1 ≤ n ≤ 10,000)이다. 둘째 줄부터 n-1개의 줄에 각 간선에 대한 정보가 들어온다. 간선에 대한 정보는 세 개의 정수로 이루어져 있다. 첫 번째 정수는 간선이 연결하는 두 노드 중 부모 노드의 번호를 나타내고, 두 번째 정수는 자식 노드를, 세 번째 정수는 간선의 가중치를 나타낸다. 간선에 대한 정보는 부모 노드의 번호가 작은 것이 먼저 입력되고, 부모 노드의 번호가 같으면 자식 노드의 번호가 작은 것이 먼저 입력된다. 루트 노드의 번호는 항상 1이라고 가정하며, 간선의 가중치는 100보다 크지 않은 양의 정수이다.

입출력 예

입력출력
12
1 2 3
1 3 2
2 4 5
3 5 11
3 6 9
4 7 1
4 8 7
5 9 15
5 10 4
6 11 6
6 12 1045

아이디어

트리 + DFS인데 와 나 그리디랑 재귀 진짜 못한다

제출 코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class four1967 {
    private static List<List<int[]>> tree;
    private static int nodeCnt;
    private static int diameter;
    private static boolean[] visited;

    public void solution() throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        nodeCnt = Integer.parseInt(reader.readLine());
        tree = new ArrayList<>();
        for (int i = 0; i < nodeCnt; i++) {
            tree.add(new ArrayList<>());
        }

        for (int i = 0; i < nodeCnt - 1; i++) {
            StringTokenizer treeToken = new StringTokenizer(reader.readLine());
            int fromNode = Integer.parseInt(treeToken.nextToken()) - 1;
            int toNode = Integer.parseInt(treeToken.nextToken()) - 1;
            int distance = Integer.parseInt(treeToken.nextToken());

            tree.get(fromNode).add(new int[] {toNode, distance});
            tree.get(toNode).add(new int[] {fromNode, distance});
        }

        diameter = 0;
        for (int i = 0; i < nodeCnt; i++) {
            visited = new boolean[nodeCnt];
            visited[i] = true;
            dfs(i, 0);
        }

        System.out.println(diameter);
    }

    private void dfs(int index, int distance) {
        for (int[] node : tree.get(index)) {
            int nextNode = node[0];
            int nextDistance = node[1];
            if (!visited[nextNode]) {
                visited[nextNode] = true;
                dfs(nextNode, distance + nextDistance);
            }
            diameter = (diameter < distance) ? distance : diameter;
        }
    }

    public static void main(String[] args) throws IOException {
        new four1967().solution();
    }
}

0개의 댓글