Skip to content

Commit 7121642

Browse files
committed
[Gold II] Title: 트리의 지름, Time: 748 ms, Memory: 80160 KB -BaekjoonHub
1 parent 2d71443 commit 7121642

2 files changed

Lines changed: 101 additions & 0 deletions

File tree

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# [Gold II] 트리의 지름 - 1167
2+
3+
[문제 링크](https://www.acmicpc.net/problem/1167)
4+
5+
### 성능 요약
6+
7+
메모리: 80160 KB, 시간: 748 ms
8+
9+
### 분류
10+
11+
그래프 이론, 그래프 탐색, 트리, 깊이 우선 탐색, 트리의 지름
12+
13+
### 제출 일자
14+
15+
2025년 11월 5일 20:25:36
16+
17+
### 문제 설명
18+
19+
<p>트리의 지름이란, 트리에서 임의의 두 점 사이의 거리 중 가장 긴 것을 말한다. 트리의 지름을 구하는 프로그램을 작성하시오.</p>
20+
21+
### 입력
22+
23+
<p>트리가 입력으로 주어진다. 먼저 첫 번째 줄에서는 트리의 정점의 개수 V가 주어지고 (2 ≤ V ≤ 100,000)둘째 줄부터 V개의 줄에 걸쳐 간선의 정보가 다음과 같이 주어진다. 정점 번호는 1부터 V까지 매겨져 있다.</p>
24+
25+
<p>먼저 정점 번호가 주어지고, 이어서 연결된 간선의 정보를 의미하는 정수가 두 개씩 주어지는데, 하나는 정점번호, 다른 하나는 그 정점까지의 거리이다. 예를 들어 네 번째 줄의 경우 정점 3은 정점 1과 거리가 2인 간선으로 연결되어 있고, 정점 4와는 거리가 3인 간선으로 연결되어 있는 것을 보여준다. 각 줄의 마지막에는 -1이 입력으로 주어진다. 주어지는 거리는 모두 10,000 이하의 자연수이다.</p>
26+
27+
### 출력
28+
29+
<p>첫째 줄에 트리의 지름을 출력한다.</p>
30+
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
import java.io.*;
2+
import java.util.*;
3+
4+
public class Main {
5+
6+
static int n, TREE_LEN, lastNode;
7+
static int[] d;
8+
static List<node>[] graph;
9+
static StringTokenizer st;
10+
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
11+
12+
public static void main(String[] args) throws Exception {
13+
inputSetting();
14+
dfs(1, 0);
15+
Arrays.fill(d, 0);
16+
dfs(lastNode, 0);
17+
System.out.println(TREE_LEN);
18+
}
19+
20+
static void dfs(int now, int pre){
21+
node next;
22+
for(int i = 0; i < graph[now].size(); i++){
23+
next = graph[now].get(i);
24+
25+
if(next.e == pre) continue;
26+
d[next.e] = d[now] + next.l;
27+
28+
if(TREE_LEN < d[next.e]){
29+
TREE_LEN = d[next.e];
30+
lastNode = next.e;
31+
}
32+
33+
dfs(next.e, now);
34+
}
35+
}
36+
37+
static void inputSetting() throws Exception {
38+
n = Integer.parseInt(br.readLine());
39+
40+
d = new int[n + 1];
41+
graph = new List[n + 1];
42+
for (int i = 0; i < n + 1; i++) {
43+
graph[i] = new ArrayList<node>();
44+
}
45+
46+
int v, e, l;
47+
for(int i = 0; i < n; i++){
48+
st = new StringTokenizer(br.readLine());
49+
50+
v = Integer.parseInt(st.nextToken());
51+
while(st.hasMoreTokens()){
52+
53+
e = Integer.parseInt(st.nextToken());
54+
55+
if(e == -1) break;
56+
l = Integer.parseInt(st.nextToken());
57+
58+
graph[v].add(new node(e, l));
59+
}
60+
}
61+
}
62+
63+
static class node {
64+
int e, l;
65+
66+
node(int e, int l) {
67+
this.e = e;
68+
this.l = l;
69+
}
70+
}
71+
}

0 commit comments

Comments
 (0)