-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ1967.java
More file actions
90 lines (84 loc) Β· 2.94 KB
/
Q1967.java
File metadata and controls
90 lines (84 loc) Β· 2.94 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/**
* Date: 2018. 9. 2.
* Author: inhyuck | https://github.com/inhyuck
* Solution URL: https://github.com/skhucode/skhucode-inhyuck
* Title: νΈλ¦¬μ μ§λ¦
* Problem: νΈλ¦¬μ μ§λ¦μ΄λ, νΈλ¦¬μμ μμμ λ μ μ¬μ΄μ 거리 μ€ κ°μ₯ κΈ΄ κ²μ λ§νλ€.
* νΈλ¦¬μ μ§λ¦μ ꡬνλ νλ‘κ·Έλ¨μ μμ±νμμ€.
* URL: https://www.acmicpc.net/problem/1967
*/
package io.inhyuck.tree;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Q1967 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int v = scanner.nextInt();
ArrayList<Edge>[] list = new ArrayList[v + 1];
for (int i = 0; i < v + 1; i++) {
list[i] = new ArrayList<>();
}
int from, to, length;
for (int i = 0; i < v - 1; i++) {
from = scanner.nextInt();
to = scanner.nextInt();
length = scanner.nextInt();
list[from].add(new Edge(to, length));
list[to].add(new Edge(from, length));
}
int[] lengthFromRoot = new int[v + 1];
bfs(v, list, lengthFromRoot, 1);
//System.out.println(Arrays.toString(lengthFromOne));
int maxLength = 0;
int maxLengthNumber = 1;
for (int i = 2; i < v + 1; i++) {
if (maxLength < lengthFromRoot[i]) {
maxLengthNumber = i;
maxLength = lengthFromRoot[i];
}
}
// System.out.println(maxLengthNumber);
int[] lengthFromMaxLengthNumber = new int[v + 1];
bfs(v, list, lengthFromMaxLengthNumber, maxLengthNumber);
maxLength = 0;
for (int i = 1; i < v + 1; i++) {
maxLength = Math.max(maxLength, lengthFromMaxLengthNumber[i]);
}
// System.out.println(Arrays.toString(lengthFromMaxLengthNumber));
System.out.println(maxLength);
}
private static void bfs(int v, ArrayList<Edge>[] list, int[] lengthFromOne, int start) {
lengthFromOne[start] = 0;
boolean[] check = new boolean[v + 1];
Queue<Integer> queue = new LinkedList<>();
queue.offer(start);
check[start] = true;
while (!queue.isEmpty()) {
int item = queue.poll();
for (Edge edge : list[item]) {
if (check[edge.to] == false) {
check[edge.to] = true;
lengthFromOne[edge.to] = lengthFromOne[item] + edge.length;
queue.offer(edge.to);
}
}
}
}
private static class Edge {
int to;
int length;
public Edge(int to, int length) {
this.to = to;
this.length = length;
}
@Override
public String toString() {
return "Edge{" +
"to=" + to +
", length=" + length +
'}';
}
}
}