https://www.acmicpc.net/problem/1167
1167번: 트리의 지름
트리가 입력으로 주어진다. 먼저 첫 번째 줄에서는 트리의 정점의 개수 V가 주어지고 (2 ≤ V ≤ 100,000)둘째 줄부터 V개의 줄에 걸쳐 간선의 정보가 다음과 같이 주어진다. 정점 번호는 1부터 V까지
www.acmicpc.net

import java.util.*;
import java.io.*;
class Point {
int point;
int weight;
public Point(int point, int weight) {
this.point = point;
this.weight = weight;
}
}
public class Main {
static LinkedList<Point> al[];
static boolean[] check;
static int n;
public static void main(String[] args) throws NumberFormatException, IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
n = Integer.parseInt(br.readLine());
al = new LinkedList[n + 1];
check = new boolean[n + 1];
for (int i = 0; i <= n; i++) {
al[i] = new LinkedList<>();
}
for (int i = 0; i < n; i++) {
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
while (b != -1) {
int w = Integer.parseInt(st.nextToken());
al[a].add(new Point(b, w));
b = Integer.parseInt(st.nextToken());
}
}
dfs(1);
System.out.println(result);
}
static int result = Integer.MIN_VALUE;
public static int dfs(int start) {
check[start] = true;
int max1 = Integer.MIN_VALUE;
int max2 = Integer.MIN_VALUE;
for (Point p : al[start]) {
if (!check[p.point]) {
int tmp;
if (max1 < (tmp = dfs(p.point) + p.weight)) {
max2 = Math.max(max2, max1);
max1 = tmp;
}
else if (max2 < tmp) {
max2 = tmp;
}
}
}
// System.out.println(start + " " + max1 + " " + max2);
if (max1 == Integer.MIN_VALUE)
return 0;
if (max2 != Integer.MIN_VALUE)
result = Math.max(result, max1 + max2);
else result = Math.max(result, max1);
return max1;
}
}

트리의 지름 문제 2개는 많이 비슷했지만 하나는 골드 4? 였고 이건 골드 2였다 흠