|
| 1 | +```java |
| 2 | +import java.io.BufferedReader; |
| 3 | +import java.io.IOException; |
| 4 | +import java.io.InputStreamReader; |
| 5 | +import java.util.*; |
| 6 | +public class Main{ |
| 7 | + static class Node{ |
| 8 | + int nv; |
| 9 | + int w; |
| 10 | + Node(int nv, int w){ |
| 11 | + this.nv = nv; this.w = w; |
| 12 | + } |
| 13 | + } |
| 14 | + private static int N; |
| 15 | + private static int R; |
| 16 | + private static List<List<Node>> tree; |
| 17 | + private static long maxLength = 0L; |
| 18 | + private static boolean[] visited; |
| 19 | + public static void main(String[] args) throws IOException { |
| 20 | + String[] temp; |
| 21 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 22 | + temp = br.readLine().split(" "); |
| 23 | + N = Integer.parseInt(temp[0] ); |
| 24 | + R = Integer.parseInt(temp[1]); |
| 25 | + |
| 26 | + visited = new boolean[N+1]; |
| 27 | + tree = new ArrayList<>(); |
| 28 | + for(int i = 0; i<N+1; i++){ |
| 29 | + tree.add(new ArrayList<>()); |
| 30 | + } |
| 31 | + |
| 32 | + for(int i = 0; i<N-1; i++){ |
| 33 | + temp = br.readLine().split(" "); |
| 34 | + int v = Integer.parseInt(temp[0]); |
| 35 | + int nv = Integer.parseInt(temp[1] ); |
| 36 | + int w = Integer.parseInt(temp[2]); |
| 37 | + tree.get(v).add(new Node(nv, w)); |
| 38 | + tree.get(nv).add(new Node(v, w)); |
| 39 | + } |
| 40 | + // 기가노드를 찾을때까지 진행 |
| 41 | + int gigaNode = 0; |
| 42 | + int iterNode = R; |
| 43 | + int height = 0; |
| 44 | + while(gigaNode == 0) { |
| 45 | + visited[iterNode] = true; |
| 46 | + List<Node> nextNodes = tree.get(iterNode); |
| 47 | + int size = 0; |
| 48 | + Node nextNode = null; |
| 49 | + for(Node node : nextNodes){ |
| 50 | + if(visited[node.nv]){ |
| 51 | + continue; |
| 52 | + } |
| 53 | + size++; |
| 54 | + nextNode = node; |
| 55 | + } |
| 56 | + // 기둥 높이 카운트 |
| 57 | + // if 기가노드 발견(자식이 2개이상) |
| 58 | + if(size > 1 || size == 0){ |
| 59 | + // - 기둥 높이 카운트 중지 & 탈출 |
| 60 | + gigaNode = iterNode; |
| 61 | + break; |
| 62 | + } |
| 63 | + height += nextNode.w; |
| 64 | + iterNode = nextNode.nv; |
| 65 | + } |
| 66 | + |
| 67 | + //System.out.println("height, giganode: "+ height + " " + gigaNode); |
| 68 | + // 기가노드에서 부터 dfs시작 |
| 69 | + dfs(gigaNode, 0); |
| 70 | + System.out.println(height + " " + maxLength); |
| 71 | + br.close(); |
| 72 | + } |
| 73 | + private static void dfs(int n, int length){ |
| 74 | + visited[n] = true; |
| 75 | + List<Node> nextNodes = tree.get(n); |
| 76 | + if(nextNodes.size() == 1){ |
| 77 | + // 리프 노드일때 |
| 78 | + maxLength = Math.max(length, maxLength); |
| 79 | + return; |
| 80 | + } |
| 81 | + for(Node nv : tree.get(n)){ |
| 82 | + if(visited[nv.nv]){ |
| 83 | + continue; |
| 84 | + } |
| 85 | + dfs(nv.nv, nv.w + length); |
| 86 | + } |
| 87 | + return; |
| 88 | + } |
| 89 | +} |
| 90 | +``` |
0 commit comments