Skip to content

Commit e35dc0b

Browse files
authored
[20251211] BOJ / G4 / 트리의 지름 / 이종환
1 parent e715fd8 commit e35dc0b

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
```java
2+
3+
import java.util.StringTokenizer;
4+
import java.util.*;
5+
import java.io.*;
6+
7+
public class Main {
8+
9+
static int nodeCnt,ans = 0;
10+
static Node[] nodes;
11+
12+
static class Node{
13+
int idx = 0;
14+
Node parent = null;
15+
HashSet<Node> set = new HashSet<>();
16+
int dis = 0;
17+
18+
public Node (int idx) {
19+
this.idx = idx;
20+
}
21+
}
22+
23+
24+
25+
public static void main(String[] args) throws IOException {
26+
init();
27+
process();
28+
print();
29+
30+
}
31+
32+
private static void init() throws IOException{
33+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
34+
nodeCnt = Integer.parseInt(br.readLine());
35+
nodes = new Node[nodeCnt+1];
36+
37+
for (int i = 1; i<= nodeCnt; i++) {
38+
nodes[i] = new Node(i);
39+
}
40+
41+
for (int i = 1; i < nodeCnt; i++) {
42+
StringTokenizer st = new StringTokenizer(br.readLine());
43+
int pNum = Integer.parseInt(st.nextToken());
44+
int cNum = Integer.parseInt(st.nextToken());
45+
int dis = Integer.parseInt(st.nextToken());
46+
Node p = nodes[pNum];
47+
Node c = nodes[cNum];
48+
c.parent = p;
49+
p.set.add(c);
50+
c.dis = dis;
51+
}
52+
}
53+
54+
private static void process() throws IOException {
55+
int rs = recursive(1);
56+
ans = Math.max(ans, rs);
57+
58+
}
59+
60+
public static int recursive(int num) {
61+
Node target = nodes[num];
62+
if(target.set.isEmpty()) return target.dis;
63+
64+
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
65+
66+
for (Node n: target.set) {
67+
pq.add(recursive(n.idx));
68+
}
69+
int longest = pq.poll();
70+
71+
if (!pq.isEmpty()) {
72+
int second = pq.poll();
73+
74+
ans = Math.max(ans, longest+second);
75+
}
76+
77+
78+
return longest + target.dis;
79+
}
80+
81+
private static void print() {
82+
System.out.println(ans);
83+
}
84+
85+
}
86+
```

0 commit comments

Comments
 (0)