[Link] https://www.acmicpc.net/problem/1991
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
import java.util.*;
import java.io.*;
public class Main {
static BufferedReader br;
static int max = 0, maxIdx = 0;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
String[] line;
int n = toi(br.readLine());
boolean[] visit = new boolean[n];
Node[] nodes = new Node[n];
for(int i = 0; i < n; i++) nodes[i] = new Node();
for(int i = 0; i < n-1; i++) {
line = getLine();
int a = toi(line[0]) - 1, b = toi(line[1]) - 1, c = toi(line[2]);
nodes[a].adj.add(new int[] { b, c });
nodes[b].adj.add(new int[] { a, c });
}
visit[0] = true;
dfs(nodes, visit, 0, 0);
Arrays.fill(visit, false);
visit[maxIdx] = true;
dfs(nodes, visit, 0, maxIdx);
print(max);
}
static void dfs(Node[] nodes, boolean[] visit, int len, int cur) {
if(len > max) {
max = len;
maxIdx = cur;
}
for(int[] arr: nodes[cur].adj) {
if(visit[arr[0]]) continue;
visit[arr[0]] = true;
dfs(nodes, visit, len + arr[1], arr[0]);
}
}
public static class Node {
ArrayList<int[]> adj = new ArrayList<int[]>();
int dis = 0;
}
static int toi(String s) { return Integer.parseInt(s); }
static String[] getLine() throws IOException { return br.readLine().split(" "); }
static <T> void print(T s) { System.out.print(s); }
static <T> void println(T s) { System.out.println(s); }
}