Skip to content

Commit e802f9b

Browse files
authored
[20250617] BOJ / G4 / 트리의 지름 / 설진영
1 parent d5ac7e8 commit e802f9b

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
```java
2+
import java.io.BufferedReader;
3+
import java.io.IOException;
4+
import java.io.InputStreamReader;
5+
import java.util.*;
6+
7+
public class Main {
8+
private static int N;
9+
private static List<Node>[] graph;
10+
private static boolean[] visited;
11+
private static int maxDistance;
12+
private static int farthestNode;
13+
14+
public static void main(String[] args) throws IOException {
15+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
16+
StringTokenizer st;
17+
18+
N = Integer.parseInt(br.readLine());
19+
graph = new List[N + 1];
20+
21+
for (int i = 1; i <= N; i++) {
22+
graph[i] = new ArrayList<>();
23+
}
24+
25+
for (int i = 0; i < N - 1; i++) {
26+
st = new StringTokenizer(br.readLine());
27+
28+
int parent = Integer.parseInt(st.nextToken());
29+
int child = Integer.parseInt(st.nextToken());
30+
int weight = Integer.parseInt(st.nextToken());
31+
32+
graph[parent].add(new Node(child, weight));
33+
graph[child].add(new Node(parent, weight));
34+
}
35+
36+
visited = new boolean[N + 1];
37+
maxDistance = 0;
38+
farthestNode = 1;
39+
dfs(1, 0);
40+
41+
visited = new boolean[N + 1];
42+
maxDistance = 0;
43+
dfs(farthestNode, 0);
44+
45+
System.out.println(maxDistance);
46+
}
47+
48+
private static void dfs(int node, int distance) {
49+
visited[node] = true;
50+
51+
if (distance > maxDistance) {
52+
maxDistance = distance;
53+
farthestNode = node;
54+
}
55+
56+
for (Node next : graph[node]) {
57+
if (!visited[next.to]) {
58+
dfs(next.to, distance + next.weight);
59+
}
60+
}
61+
}
62+
63+
static class Node {
64+
int to;
65+
int weight;
66+
67+
Node(int to, int weight) {
68+
this.to = to;
69+
this.weight = weight;
70+
}
71+
}
72+
}
73+
```

0 commit comments

Comments
 (0)