
소스코드:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
public class Main {
public static class Node {
int to;
int cost;
Node(int t, int c) {
this.to = t;
this.cost = c;
}
}
static BufferedReader br;
static BufferedWriter bw;
static int N;
static ArrayList<List<Node>> treeList;
static int maxLength;
static int farNode;
static boolean[] visited;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new OutputStreamWriter(System.out));
N = Integer.parseInt(br.readLine());
treeList = new ArrayList<>();
for (int i = 0; i <= N; i++) {
treeList.add(new ArrayList<>());
}
for (int i = 1; i < N; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int idx = Integer.parseInt(st.nextToken());
int to = Integer.parseInt(st.nextToken());
int cost = Integer.parseInt(st.nextToken());
treeList.get(idx).add(new Node(to, cost));
treeList.get(to).add(new Node(idx, cost));
}
br.close();
maxLength = 0;
farNode = 0;
visited = new boolean[N + 1];
dfs(1, 0);
Arrays.fill(visited, false);
dfs(farNode, 0);
bw.write(maxLength + "\n");
bw.close();
}
public static void dfs(int start, int sum) {
visited[start] = true;
if (sum > maxLength) {
maxLength = sum;
farNode = start;
}
for (Node nextNode : treeList.get(start)) {
if (!visited[nextNode.to]) {
dfs(nextNode.to, sum + nextNode.cost);
}
}
}
}
글의 내용 중 잘못된 점이나 수정이 필요한 부분, 혹은 궁금한 사항이 있다면 언제든 댓글로 남겨주시면 감사하겠습니다.
여러분의 피드백은 더 나은 글을 작성하는 데 큰 도움이 됩니다. 감사합니다.
'알고리즘 > 백준' 카테고리의 다른 글
| [JAVA-자바] 2448번: 별 찍기 - 11 (0) | 2025.05.05 |
|---|---|
| [JAVA-자바] 1987번: 알파벳 (0) | 2025.05.03 |
| [JAVA-자바] 1753번: 최단경로 (0) | 2025.05.02 |
| [JAVA-자바] 1504번: 특정한 최단 경로 (0) | 2025.05.02 |
| [JAVA-자바] 1043번: 거짓말 (0) | 2025.04.30 |