Skip to content

Commit 0d600f2

Browse files
committed
[20251024] BOJ / G2 / 트리의 지름 / 김민진
1 parent d9af063 commit 0d600f2

File tree

1 file changed

+98
-0
lines changed

1 file changed

+98
-0
lines changed
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
```java
2+
package etc;
3+
4+
import java.io.*;
5+
import java.util.ArrayList;
6+
import java.util.Arrays;
7+
import java.util.List;
8+
import java.util.StringTokenizer;
9+
10+
public class BJ_1167_트리의_지름 {
11+
12+
private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
13+
private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
14+
private static StringTokenizer st;
15+
16+
private static int V, ans, max, maxNode;
17+
private static int[] dist;
18+
private static List<Node>[] graph;
19+
20+
private static class Node {
21+
int to;
22+
int weight;
23+
24+
Node(int to, int weight) {
25+
this.to = to;
26+
this.weight = weight;
27+
}
28+
}
29+
30+
public static void main(String[] args) throws IOException {
31+
init();
32+
sol();
33+
}
34+
35+
private static void init() throws IOException {
36+
V = Integer.parseInt(br.readLine());
37+
ans = 0;
38+
max = 0;
39+
maxNode = 0;
40+
41+
dist = new int[V + 1];
42+
Arrays.fill(dist, -1);
43+
dist[1] = 0;
44+
45+
graph = new List[V + 1];
46+
for (int i = 1; i <= V; i++) {
47+
graph[i] = new ArrayList<>();
48+
}
49+
50+
for (int i = 0; i < V; i++) {
51+
st = new StringTokenizer(br.readLine());
52+
53+
int v = Integer.parseInt(st.nextToken());
54+
55+
int u;
56+
while ((u = Integer.parseInt(st.nextToken())) != -1) {
57+
int w = Integer.parseInt(st.nextToken());
58+
graph[v].add(new Node(u, w));
59+
}
60+
}
61+
}
62+
63+
private static void sol() throws IOException {
64+
dfs(1, 0);
65+
findMax();
66+
67+
max = 0;
68+
Arrays.fill(dist, -1);
69+
dist[maxNode] = 0;
70+
dfs(maxNode, 0);
71+
findMax();
72+
73+
bw.write(max + "");
74+
bw.flush();
75+
bw.close();
76+
br.close();
77+
}
78+
79+
private static void dfs(int v, int w) throws IOException {
80+
for (Node u : graph[v]) {
81+
if (dist[u.to] != -1) continue;
82+
83+
dist[u.to] = u.weight + w;
84+
dfs(u.to, dist[u.to]);
85+
}
86+
}
87+
88+
private static void findMax() {
89+
for (int i = 1; i <= V; i++) {
90+
if (max < dist[i]) {
91+
max = Math.max(max, dist[i]);
92+
maxNode = i;
93+
}
94+
}
95+
}
96+
97+
}
98+
```

0 commit comments

Comments
 (0)