Skip to content

Commit 88e06dd

Browse files
authored
Merge pull request #1832 from AlgorithmWithGod/LiiNi-coder
[20260125] BOJ / G4 / 트리의 지름 / 이인희
2 parents f5ed4dc + b769645 commit 88e06dd

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
```java
2+
import java.io.BufferedReader;
3+
import java.io.IOException;
4+
import java.io.InputStreamReader;
5+
import java.util.ArrayDeque;
6+
import java.util.ArrayList;
7+
import java.util.Deque;
8+
import java.util.HashMap;
9+
import java.util.List;
10+
import java.util.Map;
11+
12+
import org.w3c.dom.Node;
13+
14+
public class Main{
15+
private static int N;
16+
private static Map<Integer, List<int[]>> Graph = new HashMap<Integer, List<int[]>>();
17+
public static void main(String[] args) throws IOException {
18+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in ));
19+
N = Integer.parseInt(br.readLine());
20+
int t = N;
21+
while(t-- > 1){
22+
String[] tokens = br.readLine().split(" ");
23+
int parent = Integer.parseInt(tokens[0] );
24+
int child = Integer.parseInt(tokens[1]);
25+
int weight = Integer.parseInt(tokens[2] );
26+
Graph.putIfAbsent(parent, new ArrayList<int[]>());
27+
Graph.get(parent).add(new int[]{child, weight});
28+
Graph.putIfAbsent(child, new ArrayList<int[]>());
29+
Graph.get(child).add(new int[]{parent, weight});
30+
}
31+
if(N == 1){
32+
System.out.println(0);
33+
}else{
34+
int[] temp = bfs(1);
35+
temp = bfs(temp[0]);
36+
System.out.println(temp[1] );
37+
38+
}
39+
br.close();
40+
}
41+
42+
private static int[] bfs(int start) {
43+
Deque<int[]> q = new ArrayDeque<int[]>();
44+
boolean[] visited = new boolean[10_001];
45+
visited[start] = true;
46+
int maxDist = 0;
47+
int nodeHavingMaxDist = 0;
48+
q.offer(new int[]{start, 0});
49+
while(!q.isEmpty()){
50+
int[] qItem = q.poll();
51+
int v = qItem[0];
52+
int dist = qItem[1];
53+
for(int[] nextInfo : Graph.get(v)){
54+
int nv = nextInfo[0];
55+
int weight = nextInfo[1];
56+
if(visited[nv])
57+
continue;
58+
q.offer(new int[]{nv, dist + weight});
59+
visited[nv] = true;
60+
}
61+
if (maxDist < dist) {
62+
nodeHavingMaxDist = v;
63+
maxDist = Math.max(maxDist, dist);
64+
}
65+
}
66+
return new int[]{nodeHavingMaxDist, maxDist};
67+
}
68+
}
69+
```

0 commit comments

Comments
 (0)