Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 507f25b

Browse files
이지영: [BOJ] 1967 트리의 지름_241009
1 parent a4425d8 commit 507f25b

File tree

1 file changed

+89
-0
lines changed

1 file changed

+89
-0
lines changed

‎BOJ/1000-5000번/JY_1967.java‎

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
package day1009;
2+
3+
import java.util.*;
4+
import java.io.*;
5+
6+
public class JY_1967 {
7+
8+
static int N;
9+
static int maxLen, lastNode, ans;
10+
static List<Node>[] nrr;
11+
static boolean[] visited;
12+
static class Node {
13+
int u, dist;
14+
public Node(int u, int dist) {
15+
this.u = u;
16+
this.dist = dist;
17+
}
18+
@Override
19+
public String toString() {
20+
return "Node [u=" + u + ", dist=" + dist + "]";
21+
}
22+
23+
}
24+
25+
public static void main(String[] args) throws IOException{
26+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
27+
StringTokenizer st = new StringTokenizer(br.readLine());
28+
29+
N = Integer.parseInt(st.nextToken());
30+
nrr = new ArrayList[N+1];
31+
for(int i=1; i<N+1; i++) {
32+
nrr[i] = new ArrayList<>();
33+
}
34+
for(int i=0; i<N-1; i++) {
35+
st = new StringTokenizer(br.readLine());
36+
37+
int n1 = Integer.parseInt(st.nextToken());
38+
int n2 = Integer.parseInt(st.nextToken());
39+
int e = Integer.parseInt(st.nextToken());
40+
41+
nrr[n1].add(new Node(n2, e));
42+
nrr[n2].add(new Node(n1, e));
43+
44+
}
45+
46+
// System.out.println(Arrays.toString(nrr));
47+
48+
/**
49+
* 임의의 노드에서 가장 먼 노드를 찾고, 그 노드에서 다시 가장 먼 노드를 찾으면 트리의 지름을 구할 수 있음
50+
* 2번의 dfs 활용
51+
* 1) 임의의 노드에서 가장 먼 노드 찾기
52+
* 2) 찾은 노드로 시작하는 가장 긴 간선의 길이 찾기
53+
* */
54+
55+
// 1. 임의의 노드에서 가장 먼 노드 찾기
56+
// lastNode: 임의의 노드에서 가장 먼 노드의 길이
57+
// maxLen: 가장 먼 노드까지의 간선의 길이
58+
maxLen = Integer.MIN_VALUE;
59+
visited = new boolean[N+1];
60+
visited[1] = true;
61+
lastNode = 0;
62+
dfs(1, 0);
63+
64+
// System.out.println(maxLen+", "+lastNode);
65+
66+
// 2. 찾은 노드로 부터 가장 먼 노드까지의 길이가 트리의 지름
67+
maxLen = Integer.MIN_VALUE;
68+
visited = new boolean[N+1];
69+
visited[lastNode] = true;
70+
dfs(lastNode, 0);
71+
72+
System.out.println(maxLen);
73+
74+
}
75+
public static void dfs(int now, int len) {
76+
if(len > maxLen) {
77+
maxLen = len;
78+
lastNode = now;
79+
}
80+
81+
for(Node next: nrr[now]) {
82+
if(!visited[next.u]) {
83+
visited[next.u] = true;
84+
dfs(next.u, len+next.dist);
85+
}
86+
}
87+
}
88+
89+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /