Skip to content

Commit f282951

Browse files
committed
[BOJ] 1967 트리의 지름_241009
1 parent b67c5c7 commit f282951

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed

BOJ/1000-5000번/YJ_1967.java

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
import java.io.BufferedReader;
2+
import java.io.IOException;
3+
import java.io.InputStreamReader;
4+
import java.util.ArrayList;
5+
import java.util.List;
6+
7+
/**
8+
* 알고리즘: DFS
9+
* 시간복잡도: 1 ≤ n ≤ 10,000
10+
* 아이디어:
11+
* 트리에 존재하는 모든 경로들 중에서 가장 긴 것의 길이 구하기
12+
* DFS 1번: 루트에서 가장 멀리 있는 노드 탐색 (루트는 항상 존재하기 때문에 루트에서 시작)
13+
* DFS 2번: 해당 노드에서 가장 먼 노드 탐색 > 가장 긴 길이 계산
14+
*/
15+
16+
class Node {
17+
int node;
18+
int weight;
19+
20+
public Node(int node, int weight) {
21+
this.node = node;
22+
this.weight = weight;
23+
}
24+
}
25+
26+
public class YJ_1967 {
27+
static List<Node>[] TREE = null;
28+
static boolean[] VISITED = null;
29+
static int FAR_NODE = 0;
30+
static int longLength = 0;
31+
public static void main(String[] args) throws IOException {
32+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
33+
int N = Integer.parseInt(br.readLine());
34+
VISITED = new boolean[N+1];
35+
36+
//List index 가 하나의 노드 단위
37+
TREE = new ArrayList[N+1];
38+
for(int i=1; i<N+1; i++){
39+
TREE[i] = new ArrayList<>();
40+
}
41+
42+
//트리 생성
43+
for(int i=1; i<N; i++){
44+
String[] line = br.readLine().split("\\s");
45+
int parent = Integer.parseInt(line[0]);
46+
int child = Integer.parseInt(line[1]);
47+
int weight = Integer.parseInt(line[2]);
48+
49+
TREE[parent].add(new Node(child,weight)); //★무방향 (자식 노드로 계속 깊게 탐색)
50+
TREE[child].add(new Node(parent,weight)); //★양방향 (자식 노드에서 부모노드를 타고 다시 위로 올라오면 탐색)
51+
}
52+
//루트부터 시작하므로 방문처리
53+
int root = 1;
54+
VISITED[root] = true;
55+
56+
//1.루트에서 가장 멀리 있는 노드 탐색
57+
dfs(root,0);
58+
59+
//2.해당 노드에서 가장 먼 노드 탐색
60+
VISITED = new boolean[N+1];
61+
VISITED[FAR_NODE] = true;
62+
dfs(FAR_NODE,0);
63+
64+
System.out.println(longLength);
65+
br.close();
66+
}
67+
68+
private static void dfs(int start, int sum){
69+
longLength = Math.max(sum,longLength);
70+
if(sum == longLength){
71+
FAR_NODE = start;
72+
}
73+
74+
for(Node data : TREE[start]){
75+
int node = data.node;
76+
int weight = data.weight;
77+
78+
if(!VISITED[node]){
79+
VISITED[node] = true;
80+
dfs(node,sum+weight);
81+
VISITED[node] = false;
82+
}
83+
}
84+
}
85+
86+
}

0 commit comments

Comments
 (0)