트리의 지름

Huisu·2023년 10월 21일
0

Coding Test Practice

목록 보기
50/98
post-thumbnail

문제

1167번: 트리의 지름

문제 설명

트리의 지름이란, 트리에서 임의의 두 점 사이의 거리 중 가장 긴 것을 말한다. 트리의 지름을 구하는 프로그램을 작성하시오.

제한 사항

트리가 입력으로 주어진다. 먼저 첫 번째 줄에서는 트리의 정점의 개수 V가 주어지고 (2 ≤ V ≤ 100,000)둘째 줄부터 V개의 줄에 걸쳐 간선의 정보가 다음과 같이 주어진다. 정점 번호는 1부터 V까지 매겨져 있다.

먼저 정점 번호가 주어지고, 이어서 연결된 간선의 정보를 의미하는 정수가 두 개씩 주어지는데, 하나는 정점번호, 다른 하나는 그 정점까지의 거리이다. 예를 들어 네 번째 줄의 경우 정점 3은 정점 1과 거리가 2인 간선으로 연결되어 있고, 정점 4와는 거리가 3인 간선으로 연결되어 있는 것을 보여준다. 각 줄의 마지막에는 -1이 입력으로 주어진다. 주어지는 거리는 모두 10,000 이하의 자연수이다.

입출력 예

입력출력
5
1 3 2 -1
2 4 4 -1
3 1 2 4 3 -1
4 2 4 3 3 5 6 -1
5 4 6 -111

입출력 예 설명

아이디어

입력부가 까다로운 트리의 BFS 문제

가장 먼 거리를 이루는 두 개의 노드를 찾을 때 모든 점을 탐색하지 않아도 됨

임의의 점에서 가장 먼 거리를 가지는 노드를 찾고, 그 노드에서 다시 한번 가장 먼 거리를 가지는 노드를 찾으면 2 번의 탐색으로 가능

원으로 생각해 보면 원의 중심부에서 최장 거리를 구한 후, 거기서부터 또 최장 거리를 구한 느낌

증명 링크

[알고리즘] 트리의 지름 : Diameter of Tree

제출 코드

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

// https://www.acmicpc.net/problem/1167
public class two1167 {
    private static int nodeCnt;
    private static List<List<int[]>> edges;
    private static boolean[] visited;
    private static int[] distance;
    public void solution() throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        nodeCnt = Integer.parseInt(reader.readLine());
        edges = new ArrayList<>();
        for (int i = 0; i < nodeCnt; i++) {
            edges.add(new ArrayList<>());
        }

        for (int i = 0; i < nodeCnt; i++) {
            StringTokenizer edgeToken = new StringTokenizer(reader.readLine());
            int tokenCnt = edgeToken.countTokens();
            int from = Integer.parseInt(edgeToken.nextToken()) - 1;
            for (int j = 0; j < (tokenCnt - 2) / 2; j++) {
                int to = Integer.parseInt(edgeToken.nextToken()) - 1;
                int cost = Integer.parseInt(edgeToken.nextToken());
                edges.get(from).add(new int[] {to, cost});
            }
        }

        int maxIndex = 0;

        visited = new boolean[nodeCnt];
        distance = new int[nodeCnt];
        bfs(0);

        for (int i = 1; i < nodeCnt; i++) {
            if (distance[maxIndex] < distance[i]) {
                maxIndex = i;
            }
        }

        visited = new boolean[nodeCnt];
        distance = new int[nodeCnt];
        bfs(maxIndex);

        Arrays.sort(distance);
        System.out.println(distance[nodeCnt - 1]);
    }

    private void bfs(int startNode) {
        Queue<Integer> toVisit = new LinkedList<>();
        toVisit.add(startNode);
        visited[startNode] = true;
        while (!toVisit.isEmpty()) {
            int nowNode = toVisit.poll();
            for(int[] canVisit : edges.get(nowNode)) {
                int canNode = canVisit[0];
                int canCost = canVisit[1];
                if (!visited[canNode]) {
                    visited[canNode] = true;
                    toVisit.add(canNode);
                    distance[canNode] = distance[nowNode] + canCost;
                }
            }
        }
    }

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

0개의 댓글