/
BOJ_1967.java
67 lines (59 loc) · 1.81 KB
/
BOJ_1967.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package boj;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
/**
* 트리의 지름
* https://www.acmicpc.net/problem/1967
*/
public class BOJ_1967 {
static int answer = Integer.MIN_VALUE;
static boolean[] visited;
static int n;
static ArrayList<Node>[] tree;
static int endNode = 0;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(br.readLine());
tree = new ArrayList[n + 1];
for (int i = 1; i <= n; i++) {
tree[i] = new ArrayList<>();
}
StringTokenizer st;
for (int i = 0; i < n - 1; i++) {
st = new StringTokenizer(br.readLine());
int parent = Integer.parseInt(st.nextToken());
int child = Integer.parseInt(st.nextToken());
int weight = Integer.parseInt(st.nextToken());
tree[parent].add(new Node(child, weight));
tree[child].add(new Node(parent, weight));
}
visited = new boolean[n + 1];
dfs(n, 0);
visited = new boolean[n + 1];
dfs(endNode, 0);
System.out.println(answer);
}
private static void dfs(int current, int weight) {
if (answer < weight) {
answer = weight;
endNode = current;
}
visited[current] = true;
for (Node n : tree[current]) {
if (!visited[n.value]) {
dfs(n.value, weight + n.weight);
}
}
}
static class Node {
int value;
int weight;
Node(int value, int weight) {
this.value = value;
this.weight = weight;
}
}
}