https://www.acmicpc.net/problem/1967
1967번: 트리의 지름
파일의 첫 번째 줄은 노드의 개수 n(1 ≤ n ≤ 10,000)이다. 둘째 줄부터 n-1개의 줄에 각 간선에 대한 정보가 들어온다. 간선에 대한 정보는 세 개의 정수로 이루어져 있다. 첫 번째 정수는 간선이 연
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];
for (int i = 0; i <= n; i++) {
al[i] = new LinkedList<>();
}
check = new boolean[n + 1];
for (int i = 0; i < n - 1; i++) {
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
int w = Integer.parseInt(st.nextToken());
al[a].add(new Point(b, w));
// al[b].add(new Point(a, w));
}
if (n == 1)
System.out.println(0);
else {
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;
}
}

'baekjoon' 카테고리의 다른 글
| <java> 백준 16236 아기 상어 (1) | 2022.10.15 |
|---|---|
| <java> 백준 9466 텀 프로젝트 (0) | 2022.10.14 |
| <java> 백준 1707 이분 그래프 (1) | 2022.10.13 |
| <java> 백준 1022 소용돌이 예쁘게 출력하기 (1) | 2022.10.11 |
| <java> 백준 17845 수강과목 (0) | 2022.10.07 |