https://www.acmicpc.net/problem/1967
정답률 40.769%
트리(tree)는 사이클이 없는 무방향 그래프이다. 트리에서는 어떤 두 노드를 선택해도 둘 사이에 경로가 항상 하나만 존재하게 된다. 트리에서 어떤 두 노드를 선택해서 양쪽으로 쫙 당길 때, 가장 길게 늘어나는 경우가 있을 것이다. 이럴 때 트리의 모든 노드들은 이 두 노드를 지름의 끝 점으로 하는 원 안에 들어가게 된다.

이런 두 노드 사이의 경로의 길이를 트리의 지름이라고 한다. 정확히 정의하자면 트리에 존재하는 모든 경로들 중에서 가장 긴 것의 길이를 말한다.
입력으로 루트가 있는 트리를 가중치가 있는 간선들로 줄 때, 트리의 지름을 구해서 출력하는 프로그램을 작성하시오. 아래와 같은 트리가 주어진다면 트리의 지름은 45가 된다.

트리의 노드는 1부터 n까지 번호가 매겨져 있다.
12
1 2 3
1 3 2
2 4 5
3 5 11
3 6 9
4 7 1
4 8 7
5 9 15
5 10 4
6 11 6
6 12 10
45
입력 형식과 루트 노드가 1번으로 고정돼 있다는 점만 제외하면 1167번 문제와 동일한 문제다.
풀이 아이디어는 임의의 노드 A에서 가장 멀리 떨어진 노드 B를 구하고, B에서 다시 가장 멀리 떨어진 노드 C를 구한 뒤 B와 C의 거리가 트리의 지름이 된다.
주의할 점은 노드의 개수 n의 범위가 1부터 시작되므로 1일 때는 따로 처리해줘야 예외가 발생하지 않는다.
//백준
public class Main {
static HashMap<Integer, List<Edge>> adjList = new HashMap<>();
static int[] dist; //각 노드까지의 누적 거리
static boolean[] visited;
public static void main(String[] args) throws IOException {
System.setIn(new FileInputStream("src/input.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
dist = new int[N + 1];
visited = new boolean[N + 1];
if (N == 1) { //노트가 1개일 때
System.out.println(0);
return;
}
for (int i = 0; i <= N; i++) {
adjList.put(i, new ArrayList<>());
}
for (int i = 0; i < N - 1; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int start = Integer.parseInt(st.nextToken());
int end = Integer.parseInt(st.nextToken());
int weight = Integer.parseInt(st.nextToken());
adjList.get(start).add(new Edge(end, weight));
adjList.get(end).add(new Edge(start, weight));
}
//루트 노드에서 dfs
dfs(1, 0);
int max = 0, maxNode = 0;
for (int i = 1; i <= N; i++) {
if (max < dist[i]) {
max = dist[i];
maxNode = i;
}
}
//루트 노드에서 가장 멀리 떨어진 노드에서 dfs
dfs(maxNode, 0);
Arrays.stream(dist)
.max()
.ifPresent(System.out::println);
}
static void dfs(int start, int weight) {
//누적 거리 갱신
if (dist[start] < weight) {
dist[start] = weight;
}
//인접 노드 탐색
for (Edge edge : adjList.get(start)) {
if (!visited[edge.end]) { //방문하지 않은 노드일 경우
//현 노드는 방문 처리 후 재귀 호출
visited[start] = true;
dfs(edge.end, weight + edge.weight);
//재귀 호출이 끝나면 현 노드는 미방문 처리
visited[start] = false;
}
}
}
static class Edge {
int end;
int weight;
public Edge(int end, int weight) {
this.end = end;
this.weight = weight;
}
}
}