베오
DCode
베오
전체 방문자
오늘
어제
  • 분류 전체보기 (218)
    • 공지사항 (1)
    • 잡설 (1)
    • Programming (33)
      • [C] (1)
      • [Java] (4)
      • [Python] (2)
      • [Android] (2)
      • [Network] (0)
      • [Operation System] (2)
      • [Spring Boot] (22)
      • [Docker] (0)
    • Algorithm (31)
      • 자료구조 (2)
      • 알고리즘 (Java) (14)
      • 알고리즘 (기초) (15)
    • Coding Test (131)
      • BOJ (131)
      • Algospat (0)
    • 이론적인거 (14)
      • 보안 (5)
      • 오류 해결 (2)
      • 디자인 패턴 (5)
      • 네트워크 (1)
      • 기타 (1)
    • 최신기술 (4)
      • 블록체인 (1)
    • [Project] (1)

블로그 메뉴

  • 🐈‍⬛ GitHub
  • 📫 방명록
  • 🔖 태그

공지사항

인기 글

티스토리

hELLO · Designed By 정상우.
베오

DCode

Coding Test/BOJ

[BOJ/JAAVA] 1967번: 트리의 지름

2022. 11. 14. 20:45

https://www.acmicpc.net/problem/1967

 

1967번: 트리의 지름

파일의 첫 번째 줄은 노드의 개수 n(1 ≤ n ≤ 10,000)이다. 둘째 줄부터 n-1개의 줄에 각 간선에 대한 정보가 들어온다. 간선에 대한 정보는 세 개의 정수로 이루어져 있다. 첫 번째 정수는 간선이 연

www.acmicpc.net

키워드

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


구현

  • 주어진 정보를 이용하여 트리를 구현한다.
  • 모든 노드를 돌면서 현재 노드 위치를 루트로 하는 서브트리에서 루트를 무조건 거치는 최대 길이를 구한다.

코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.StringTokenizer;

public class java_1967 {
    static int n;

    static ArrayList<Node> tree;

    static List<Integer> leafNode;

    static boolean[] isVisited;

    static class Node {
        boolean isLeafNode;
        List<Pair> adj;

        public Node() {
            this.isLeafNode = true;
            this.adj = new ArrayList<>();
        }

        @Override
        public String toString() {
            return "Node [isLeafNode=" + isLeafNode + ", adj=" + adj + "]";
        }

    }

    static class Pair {
        int cost, child;

        public Pair(int cost, int child) {
            this.cost = cost;
            this.child = child;
        }

        @Override
        public String toString() {
            return "Pair [cost=" + cost + ", child=" + child + "]";
        }
    }

    // 현재 노드로부터 자식 노드
    static int calcRadius(int node) {
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();
        priorityQueue.add(0);
        priorityQueue.add(0);

        for (int i = 0; i < tree.get(node).adj.size(); i++) {
            int targetNode = tree.get(node).adj.get(i).child;

            isVisited = new boolean[n];
            isVisited[targetNode] = true;
            isVisited[node] = true;
            int tmp = calcLength(targetNode) + tree.get(node).adj.get(i).cost;

            priorityQueue.add(tmp);
            priorityQueue.poll();
        }

        return priorityQueue.poll() + priorityQueue.poll();
    }

    // node를 루트로하는 가장 긴 길이 반환
    static int calcLength(int here) {
        if (tree.get(here).isLeafNode) {
            return 0;
        }

        int result = 0;

        for (int i = 0; i < tree.get(here).adj.size(); i++) {
            if (!isVisited[tree.get(here).adj.get(i).child]) {
                isVisited[tree.get(here).adj.get(i).child] = true;
                result = Math.max(result, calcLength(tree.get(here).adj.get(i).child) + tree.get(here).adj.get(i).cost);
            }
        }

        return result;
    }

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

        n = Integer.parseInt(br.readLine());
        // 한 말단에서 다른 말단 까지 거리

        // 두 노드의 최소 공통 조상 찾기

        tree = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            tree.add(new Node());
        }

        for (int i = 0; i < n - 1; i++) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            int parent = Integer.parseInt(st.nextToken()) - 1;
            int child = Integer.parseInt(st.nextToken()) - 1;
            int cost = Integer.parseInt(st.nextToken());

            tree.get(parent).adj.add(new Pair(cost, child));
            tree.get(child).adj.add(new Pair(cost, parent));
            tree.get(parent).isLeafNode = false;
        }

        // for (int i = 0; i < tree.size(); i++) {
        // System.out.println(tree.get(i));
        // }

        int result = 0;
        // 현재 노드로부터 왼쪽 최대합 + 오른쪽 최대합 구하기
        for (int i = 0; i < n; i++) {
            int radius = calcRadius(i);
            result = Math.max(result, radius);
        }

        System.out.println(result);

        br.close();
    }
}

저작자표시 (새창열림)

'Coding Test > BOJ' 카테고리의 다른 글

[BOJ/JAVA] 23351번: 물주기  (0) 2022.11.21
[BOJ/JAVA] 10709번: 기상캐스터  (0) 2022.11.21
[BOJ/JAVA] 15681번: 트리와 쿼리  (1) 2022.11.14
[BOJ/JAVA] 9934번: 완전 이진 트리  (0) 2022.11.14
[BOJ/JAVA] 11725번: 트리의 부모 찾기  (0) 2022.11.14
    'Coding Test/BOJ' 카테고리의 다른 글
    • [BOJ/JAVA] 23351번: 물주기
    • [BOJ/JAVA] 10709번: 기상캐스터
    • [BOJ/JAVA] 15681번: 트리와 쿼리
    • [BOJ/JAVA] 9934번: 완전 이진 트리
    베오
    베오

    티스토리툴바