|
| 1 | +import java.io.*; |
| 2 | +import java.util.*; |
| 3 | + |
| 4 | +public class Beakjoon_1167 { |
| 5 | + static int V; |
| 6 | + static ArrayList<Edge>[] tree; |
| 7 | + static boolean[] visited; |
| 8 | + static int farthestNode; |
| 9 | + static int maxDistance; |
| 10 | + |
| 11 | + static class Edge { |
| 12 | + int to; |
| 13 | + int weight; |
| 14 | + public Edge(int to, int weight) { |
| 15 | + this.to = to; |
| 16 | + this.weight = weight; |
| 17 | + } |
| 18 | + } |
| 19 | + |
| 20 | + public static void main(String[] args) throws IOException { |
| 21 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 22 | + V = Integer.parseInt(br.readLine().trim()); |
| 23 | + tree = new ArrayList[V + 1]; |
| 24 | + for (int i = 1; i <= V; i++) { |
| 25 | + tree[i] = new ArrayList<>(); |
| 26 | + } |
| 27 | + |
| 28 | + for (int i = 0; i < V; i++) { |
| 29 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 30 | + int from = Integer.parseInt(st.nextToken()); |
| 31 | + while (true) { |
| 32 | + int to = Integer.parseInt(st.nextToken()); |
| 33 | + if (to == -1) break; |
| 34 | + int w = Integer.parseInt(st.nextToken()); |
| 35 | + tree[from].add(new Edge(to, w)); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + visited = new boolean[V + 1]; |
| 40 | + visited[1] = true; |
| 41 | + dfs(1, 0); |
| 42 | + |
| 43 | + visited = new boolean[V + 1]; |
| 44 | + visited[farthestNode] = true; |
| 45 | + maxDistance = 0; |
| 46 | + dfs(farthestNode, 0); |
| 47 | + |
| 48 | + System.out.println(maxDistance); |
| 49 | + } |
| 50 | + |
| 51 | + static void dfs(int cur, int dist) { |
| 52 | + if (dist > maxDistance) { |
| 53 | + maxDistance = dist; |
| 54 | + farthestNode = cur; |
| 55 | + } |
| 56 | + for (Edge e : tree[cur]) { |
| 57 | + if (!visited[e.to]) { |
| 58 | + visited[e.to] = true; |
| 59 | + dfs(e.to, dist + e.weight); |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | +} |
0 commit comments