Skip to content

Commit 178f815

Browse files
authored
Merge pull request #221 from AlgorithmWithGod/suyeun84
[20250310] BOJ / G4 / 트리의 지름 / 김수연
2 parents 29fa3df + 9565df6 commit 178f815

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
```java
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class boj1967 {
6+
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
7+
static StringTokenizer st;
8+
static void nextLine() throws Exception {st = new StringTokenizer(br.readLine());}
9+
static int nextInt() {return Integer.parseInt(st.nextToken());}
10+
11+
static ArrayList<ArrayList<Node>> graph;
12+
static boolean[] visited;
13+
static int answer = 0;
14+
public static void main(String[] args) throws Exception {
15+
nextLine();
16+
int n = nextInt();
17+
graph = new ArrayList<>(n+1);
18+
visited = new boolean[n+1];
19+
for (int i = 0; i < n+1; i++) graph.add(new ArrayList<>());
20+
for (int i = 0; i < n-1; i++) {
21+
nextLine();
22+
int a = nextInt();
23+
int b = nextInt();
24+
int c = nextInt();
25+
graph.get(a).add(new Node(b, c));
26+
graph.get(b).add(new Node(a, c));
27+
}
28+
29+
for (int i = 1; i <= n; i++) {
30+
if (graph.get(i).size() != 1) continue;
31+
visited[i] = true;
32+
dfs(i, 0);
33+
visited[i] = false;
34+
}
35+
System.out.println(answer);
36+
}
37+
38+
static void dfs(int node, int total) {
39+
for (Node n : graph.get(node)) {
40+
if (visited[n.n]) continue;
41+
visited[n.n] = true;
42+
dfs(n.n, total + n.c);
43+
visited[n.n] = false;
44+
}
45+
answer = Math.max(answer, total);
46+
}
47+
48+
static class Node {
49+
int n;
50+
int c;
51+
public Node(int n, int c) {
52+
this.n = n;
53+
this.c = c;
54+
}
55+
}
56+
}
57+
58+
```

0 commit comments

Comments
 (0)