https://www.acmicpc.net/problem/19581
19581번: 두 번째 트리의 지름
트리에 N개의 정점이 있고, 각 정점 별로 1부터 N까지의 번호가 붙어있다. 트리에서 가장 먼 두 정점 간의 거리를 트리의 지름이라고 한다. 트리의 지름을 구하는 문제는 너무 많기 때문에 우리
www.acmicpc.net
문제
풀이
트리의 지름을 구하기위해 다음과 같은 방법을 이용해서 구할 수 있었다.
1. 아무노드(1)에서 탐색을하여 제일 먼 것(a)을 선택.
2. 선택한 제일 먼 노드(a)에서 제일 먼 노드를 선택(b)
a<->b 의 거리가 트리의 지름이다.
그러나 , 이 문제에서는 조건이 하나 더 추가된다.
두번째 큰 지름을 구하는것. 위의 1,2번 까지는 똑같이 하면된다.
3. a에서 출발하여 b를 제외한 제일 먼 노드를 선택(c)
4. b에서 출발하여 a를 제외한 제일 먼 노드를 선택(d)
a<->c 와 b<->d 중 max값이 정답이다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
import java.util.*;
import java.io.*;
import java.util.stream.Collectors;
public class Main{
static int N;
static boolean[] visit;
static ArrayList<Node>[] list;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
list = new ArrayList[N+1];
for(int i=1;i<=N;i++)
list[i] = new ArrayList<>();
for(int i=1;i<N;i++){
int[] input = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
list[input[0]].add(new Node(input[1],input[2]));
list[input[1]].add(new Node(input[0],input[2]));
}
Node node1 = bfs(1, 0);
Node node2 = bfs(node1.node, 0);
Node result1 = bfs(node1.node, node2.node);
Node result2 = bfs(node2.node, node1.node);
System.out.println(Math.max(result1.weight,result2.weight));
}
static Node bfs(int start,int exNode){
LinkedList<Node> q = new LinkedList<>();
q.add(new Node(start,0));
Node retNode = new Node(start, 0);
visit = new boolean[N+1];
while (!q.isEmpty()){
Node cur = q.poll();
visit[cur.node]=true;
if(cur.weight > retNode.weight && cur.node!=exNode)
retNode = cur;
for (Node next : list[cur.node]) {
if(!visit[next.node] && next.node!=exNode)
q.add(new Node(next.node,cur.weight+next.weight));
}
}
return retNode;
}
static class Node{
int node;
int weight;
public Node(int node, int weight) {
this.node = node;
this.weight = weight;
}
}
}
|
cs |
'알고리즘,PS > 백준' 카테고리의 다른 글
[BOJ] 백준 [11054] 가장 긴 바이토닉 부분 수열 JAVA (0) | 2021.10.13 |
---|---|
[BOJ] 백준 [2150] 강한 결합 요소 JAVA (0) | 2021.10.08 |
[BOJ] 백준 [5719] 거의 최단 경로 JAVA (0) | 2021.10.02 |
[BOJ] 백준 [2533] 사회망 서비스(SNS) JAVA (0) | 2021.09.30 |
[BOJ] 백준 [9252] LCS 2 JAVA (0) | 2021.09.29 |