|
| 1 | +package Tree.P1167; |
| 2 | + |
| 3 | +import java.io.*; |
| 4 | +import java.util.*; |
| 5 | + |
| 6 | +public class Main { |
| 7 | + |
| 8 | + static int V, max = Integer.MIN_VALUE, root, dist; |
| 9 | + static ArrayList<Node>[] tree; |
| 10 | + static boolean[] visited; |
| 11 | + |
| 12 | + public static void main(String[] args) throws Exception { |
| 13 | + System.setIn(new FileInputStream("src/Tree/P1167/input.txt")); |
| 14 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 15 | + |
| 16 | + V = Integer.parseInt(br.readLine()); |
| 17 | + tree = new ArrayList[V+1]; |
| 18 | + |
| 19 | + for (int i = 1; i <= V; i++) { |
| 20 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 21 | + int from = Integer.parseInt(st.nextToken()), to, dist; |
| 22 | + tree[from] = new ArrayList<>(); |
| 23 | + while ((to = Integer.parseInt(st.nextToken())) != -1) { |
| 24 | + dist = Integer.parseInt(st.nextToken()); |
| 25 | + tree[from].add(new Node(to, dist)); |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + visited = new boolean[V+1]; |
| 30 | + dfs(1, 0); |
| 31 | + visited = new boolean[V+1]; |
| 32 | + dfs(root, 0); |
| 33 | + |
| 34 | + System.out.println(max); |
| 35 | + } |
| 36 | + |
| 37 | + static void dfs(int cur, int dist) { |
| 38 | + visited[cur] = true; |
| 39 | + for (Node node : tree[cur]) { |
| 40 | + if (!visited[node.to]) { |
| 41 | + dfs(node.to, dist + node.dist); |
| 42 | + } |
| 43 | + } |
| 44 | + if (dist > max) { |
| 45 | + max = dist; |
| 46 | + root = cur; |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + static class Node { |
| 51 | + int to, dist; |
| 52 | + |
| 53 | + public Node(int to, int dist) { |
| 54 | + this.to = to; |
| 55 | + this.dist = dist; |
| 56 | + } |
| 57 | + } |
| 58 | +} |
0 commit comments